C# 3.0 looks like Smalltak

By Fons Sonnemans, 14-9-2005

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 {
    static void Main(string[] args) {
        Console.WriteLine(5.IsPrime()); // true
        Console.WriteLine(9.IsPrime()); // false
        Console.WriteLine(23.IsPrime()); // true
    }
}

static class Extensions {

    public static bool IsPrime(this int number) {
        if (number == 1 || number == 2 || number == 3) {
            return true;
        }
        if ((number % 2) == 0) {
            return false;
        }
        int sqrt = (int)Math.Sqrt(number);
        for (int t = 3; t <= sqrt; t = t + 2) {
            if (number % t == 0) {
                return false;
            }
        }
        return true;
    }
}
Tags: CSharp

Leave a Comment

Leave a Comment
Name
Comment
5 + 1 =

0 Comments

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.