C# 3.0 looks like Smalltak

By Fons Sonnemans, posted on 14-Sep-2005
1 Comments

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.

class Program {
   &nbspstaticvoid Main(string[]args){
   &nbsp   &nbspConsole.WriteLine(5.IsPrime());// true
   &nbsp   &nbspConsole.WriteLine(9.IsPrime());// false
   &nbsp   &nbspConsole.WriteLine(23.IsPrime());// true
   &nbsp}
}

staticclass Extensions {

   &nbsppublicstaticbool IsPrime(thisintnumber){
   &nbsp   &nbspif(number==1||number==2||number==3){
   &nbsp   &nbsp   &nbspreturntrue;
   &nbsp   &nbsp}
   &nbsp   &nbspif((number%2)==0){
   &nbsp   &nbsp   &nbspreturnfalse;
   &nbsp   &nbsp}
   &nbsp   &nbspintsqrt=(int)Math.Sqrt(number);
   &nbsp   &nbspfor(int t =3; t <=sqrt; t = t +2){
   &nbsp   &nbsp   &nbspif(number% t ==0){
   &nbsp   &nbsp   &nbsp   &nbspreturnfalse;
   &nbsp   &nbsp   &nbsp}
   &nbsp   &nbsp}
   &nbsp   &nbspreturntrue;
   &nbsp}
}

Tags

CSharp

All 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.

Leave a comment

Blog comments

0 responses