Friday, August 27, 2010

c#3.0 enhancements for SharePoint developers

SharePoint 2010 adds the capability of LINQ, we would probably use this more for queries than CAML. Additionally, if we are dishing out client object model code, LINQ queries and lambda expressions (=>) are good to know. Now they have been in existence for a couple of years but we, the flock of SP coders, have always been slow adopter of new language and framework features; time to get used to them.

Before getting on with LINQ having an understanding of C# 3.0 language enhancement (=> included) is important.

Here is a piece of code that gives an example of each of these enhancements


namespace CHash3Enhancements
{
    class Person
    {
        public int Age { get; set; }
        public string Name{ get; set; }


    }
    
    static class Enhancements // static required for method extensions
    {
        // static method extensions
        static int GetAgeAfter5Years(this Person o) // note the this keyword in args here
        {
            var ageAfter5 = o.Age + 5;
            return ageAfter5;
        }


        static double GetAveragePositiveValue(this IEnumerable<int> o) // note the this keyword here
        {
            var avg = o.Where(a => a >= 0).Sum() / o.Count(a => a >= 0); ;
            return avg;
        }




        static void Main(string[] args)
        {
            // implicitly typed variables
            var i = 1;
            var str = "abc";
            // collection and method initialization
            var person = new Person() { Age = 20, Name = "partha" };
            var persons = new Person[] { new Person { Age = 20, Name = "ab" }, new Person { Age = 20, Name = "sv" } };
            var intarr = new int[] { -5, 4, 1, 2, 3 };
            // lambda expressions
            var lt3arr = intarr.TakeWhile(a => a < 3);
            Console.WriteLine(lt3arr.Count(a => a>1));


            // static method extensions
            Console.WriteLine("Avg Positive: {0}", intarr.GetAveragePositiveValue());
            Console.WriteLine("Age after 5: {0}", person.GetAgeAfter5Years());


            // anonymous types
            var anonymousperson = new { Age = 12, Name = "jack", addProp = "look" };
            Console.WriteLine("that anon vals are {0} and {1}", anonymousperson.Age, anonymousperson.addProp);


            Console.WriteLine("the implicity defined values are {0} and {1}", intarr[2], str);
            Console.WriteLine("the initialized values are {0} and {1}", persons[0].Age, persons[1].Name);
            Console.Read();
        }
    }
}


 An important understanding to have here is this: None of the enhancements shown above are framework enhancements, the .net framework has not changed a bit; these are only  language and compiler enhancements

No comments: