Many years ago I programmed in Smalltalk (Enfin which later became ObjectStudio). I have always liked it although it was not very programmer friendly (no IntelliSense). I have just wachted this C# 3.0 Language Enhancements in action video. The shown Extension Methods feature realy looks like the Secondary Class files of Smalltalk. Nice to see them back, they where very handy.
In the following example I have added the 'IsPrime()' method to the 'Int32' type. The 'this' keyword in front of the 'number' parameter of the IsPrime() method did the real trick. This makes it an Extension Method.
 staticvoid Main(string[]args){
   Console.WriteLine(5.IsPrime());// true
   Console.WriteLine(9.IsPrime());// false
   Console.WriteLine(23.IsPrime());// true
 }
}
staticclass Extensions {
 publicstaticbool IsPrime(thisintnumber){
   if(number==1||number==2||number==3){
     returntrue;
   }
   if((number%2)==0){
     returnfalse;
   }
   intsqrt=(int)Math.Sqrt(number);
   for(int t =3; t <=sqrt; t = t +2){
     if(number% t ==0){
       returnfalse;
     }
   }
   returntrue;
 }
}
Tags
CSharpAll postings/content on this blog are provided "AS IS" with no warranties, and confer no rights. All entries in this blog are my opinion and don't necessarily reflect the opinion of my employer or sponsors. The content on this site is licensed under a Creative Commons Attribution By license.
Blog comments
0 responses