April, 2007

  • Wriju's BLOG

    C# 3.0 Enhancements: Extension Methods

    • 4 Comments

    Extension Methods are different way of implementing static method. In C# 3.0 it allows us to extend any type and add method for that type. While writing extension method you need to

    Ø       declare a public static method

    Ø       the first parameter of that method should be the type of the object

    Ø       this” keyword has to be the first part of the first argument of that method

     

    This helps us to extend methods for the types that are already part of .NET Framework.

     

    If you have declared an Extension Method like

     

    public static void Foo(this string sVal)

    {

        //Do something

    }

     

    If you make a call to this method the syntax will look like,

     

    string s = "Something for test";

    s.Foo();

     

    The actual call will happen like

    myExtensions.Foo(s); Here myExtensions is the static class under which you have defined the Foo method.

     

    Another first class treatment of static method in .NET. It allows us to feel the magic as if we are writing CLR code. You can define most of your utility functions in form of extension method and by using the “using” block you can use them in your code behind file.

     

     

    The real life example of the extension method may look like,

     

    public static class myExtensions

    {

        public static string GetString(this string[] arrStr)

        {

            StringBuilder sb = new StringBuilder();

     

            foreach (string s in arrStr)

            {

                if (sb.Length != 0)

                    sb.Append(",");

                   

                    sb.Append(s);               

            }

            return sb.ToString();

        }      

    }

     

     

    class Program

    {        

        static void Main(string[] args)

        {

            string[] sTest = new string[]

    { "Wriju", "Writam", "Deb", "Sumitra" };

     

            Console.WriteLine(sTest.GetString());

            Console.ReadKey();

        }                       

    }

     

     

    Namoskar!!!

  • Wriju's BLOG

    C# 3.0 Enhancements: Collection Initializers

    • 4 Comments

    In C# 3.0 we can easily initialize collection. It is smarter and concise way of writing code.

     

    There are couple of things we should consider while initializing the collection.

    Ø       The collection should implement ICollection<T>

    Ø       The collection should have a provision to invoke ICollection<T>.Add(T)

     

     

    Here is couple of them. I am sure that you are very excited.

     

    //Array of string initialization

    string[] sTest = new string[]

    { "Wriju", "Writam", "Deb", "Sumitra" };

     

    //Dictionary object initialization

    Dictionary<int, string> objDic =

    new Dictionary<int, string>

    { { 0, "Zero" }, { 1, "One" } };

     

    //Generic Initialization

    List<Cust> objCusts = new List<Cust>{

    new Cust{ID=1, Name="Wriju"},

         new Cust{ID=2, Name="Writam"},

         new Cust{ID=3, Name="Deb"},

         new Cust{ID=4, Name="Sumitra"}};

     

    Namoskar!!!

  • Wriju's BLOG

    C# 3.0 Enhancements: Object Initializers

    • 3 Comments

    C# 3.0 allows us to initialize object in far better way in one single line. Let’s talk with an example here. Back again to my favorite Customer object.

     

    public class Customer

    {

        public Customer() { }

     

        private int _ID;

        public int ID

        {

            get { return _ID; }

            set { _ID = value; }

        }

     

        private string _Name;

        public string Name

        {

            get { return _Name; }

            set { _Name = value; }

        }    

    }

     

    If you want to initialize the properties with the object initialization current style won’t allow you to do so. What you can do is that you can create another public parameterized constructor, like

     

    public Customer(int intCustID, string sCustName)

    {

        _ID = intCustID;

        _Name = sCustName;

    }

     

    Now internally this will initialize the property. But you may not require to set values to property every time. C# 3.0 rescues us where we can initialize the Customer class with property even though there is just a default public constructor.

     

     

    Customer objCust = new Customer() {ID = 1,Name = "Wriju"};

     

    Now if you do not want to set all the properties you can freely chose one or any number. It does not force you to initialize all the properties every time.

     

    Customer objCust = new Customer { Name = "Wriju" };

     

    Amazing feature.

     

    Namoskar!!!

  • Wriju's BLOG

    Linq to Object: Play with OS Component

    • 1 Comments

     

    Linq not only allows us to work with .NET objects but also gives us the power to play with OS components like EventLog, Registry, Processes etc. If you plan to develop tool which will monitor the system process activities and will notify admin if there is any unpredictable things happening. It is all about writing your own admin tool.

    You need to have using System.Diagnostics on top of your page.

     

    In Orcas Beta 1 code looks like,

     

    var ProcessQuery = from p in Process.GetProcesses()

                       orderby p.PagedMemorySize64 descending

                       select new {

    Name = p.ProcessName,

    Size = p.PagedMemorySize64

    };

     

    foreach (var aa in ProcessQuery)

    {

        Console.WriteLine(" [ " + aa.Size + " ] " + aa.Name);

    }

     

    I love LINQ. It is ……….

     

    And the output is….

     

     [ 62271488 ] devenv

     [ 40300544 ] sqlservr

     [ 39219200 ] svchost

     [ 28323840 ] CSharp3_23Apr.vshost

     [ 16941056 ] CcmExec

     [ 16150528 ] InoTask

     [ 15310848 ] winlogon

     [ 15220736 ] InoRT

     [ 9261056 ] explorer

     [ 8540160 ] lsass

     [ 6107136 ] inetinfo

     [ 4919296 ] InoRpc

     [ 4702208 ] services

     [ 4599808 ] spoolsv

     [ 4210688 ] wmiprvse

     [ 3592192 ] svchost

     [ 3072000 ] svchost

     [ 3031040 ] winlogon

     [ 2322432 ] svchost

     [ 2064384 ] wmiprvse

     [ 1810432 ] csrss

     [ 1572864 ] GrooveMonitor

     [ 1568768 ] svchost

     [ 1531904 ] wdfmgr

     [ 1486848 ] rdpclip

     [ 1441792 ] igfxtray

     [ 1355776 ] alg

     [ 1142784 ] FwcAgent

     [ 1081344 ] FwcMgmt

     [ 942080 ] sqlbrowser

     [ 933888 ] sqlwriter

     [ 929792 ] ctfmon

     [ 741376 ] csrss

     [ 385024 ] logon.scr

     [ 155648 ] smss

     [ 0 ] System

     [ 0 ] Idle

     

     

     

    Namoskar!!!

  • Wriju's BLOG

    C# 3.0 Enhancements: Expression Trees

    • 1 Comments

    Expression Tree is the feature which enables us to write function which can be complied on-demand basis. It stores the function in form of structured data rather than executable code. Since this is structured we can easily iterate through it anytime. This is easier than finding something in IL.

     

    Let’s suppose if you have code like

     

    Func<int, int> f = x => x * 5;

    Console.WriteLine(f(30));

     

    and you execute it. This will execute normally.

     

    But what if you want to store the whole function body in IL and compile as and when required. Then the above code look little different.

     

    Expression<Func<int, int>> e = x => x * 5;

     

    Now you cannot execute expression like function. But you can see the body of the expression in Expression Tree Visualizer. To use Expression you need to use the namespace System.Linq.Expressions

     

    So if you use the code like

     

    Console.WriteLine(e);

     

    The output will look like, x => (x * 5) instead of some kind of perfect integer values. Now if you want to use the function written there in Expression Tree you need little different approach,

     

    var f = e.Compile();

    Console.WriteLine(f(30));

     

    Compile statement will compile the IL code and your function will be ready for execution.

     

    If you want to write your own Expression instead of using the Expression <> to convert the delegate to function call, .NET allows us to do that. The Expression representation of the above f = x => x * 5; will look like

     

    ParameterExpression x = Expression.Parameter(typeof(int), "x");

    Expression body = Expression.Multiply(x, Expression.Constant(5));

    Expression<Func<int, int>> e = Expression.Lambda<Func<int, int>>(body, x);

     

     

     

    This happens exactly when you use SQL statement and execute it SQL Server database. Internally it creates functions and send to the compiler, then compiler compiles the code during the execution. Various rules engine like BizTalk uses this concept.

     

    Now if you put a break point on e and hover over it during debug you can get the Expression Tree out of it.

     

     

    I am loving itJ

     

    Namoskar!!!

     

     

  • Wriju's BLOG

    C# 3.0 Enhancements: Expression Trees (recording)

    • 1 Comments

    I have discussed about the Expression Trees in my previous blog at C# 3.0 Enhancements: Expression Trees. I have done a small recording on that showing the demo there. I have uploaded that to MSN Soapbox and you can find that here.

     


    Video: CSharp 3.0 Expression Trees 

     

    Namoskar!!!

  • Wriju's BLOG

    C# 3.0 Enhancements: Lambda Expression

    • 0 Comments

    After a pretty long time I am again back to the Blog business. During these days I was busy preparing myself on C# 3.0 for our ISV Developers. I started giving demos to them and during my study I found a good number of exciting features which C# 3.0 offers in a nutshell. I will talk about them one by one. Let’s start with Lambda expression.

     

    Lambda Expressions are giving first class treatment to delegate and functions. When you are dealing with Lambda Expressions then you are surely dealing with Delegates.

     

    Let’s assume this example.

     

    //Array of integers

    List<int> arrInt =

    new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

     

    //Using Predicate we are finding the even numbers

    List<int> even1 =

    arrInt.FindAll(new Predicate<int>(EvenGetter));

     

    foreach(int i1 in even1)

        Console.WriteLine(i1);

     

    Console.ReadKey();

     

    This retrieves the even numbers from the collection. But you need another method

    static bool EvenGetter(int i)

    {

        return i % 2 == 0;

    }

     

     

    In C# 2.0 we have introduced little smarter way. You can add inline function using the keyword delegate. The code looks like,

     

    //Using delegate keyword, more smarter way

    List<int> even1 = arrInt.FindAll(delegate(int i2)

    { return i2 % 2 == 0; });

     

    This does not require any extra function in the application. But it is still painful.

     

    Lambda Expression helps us to write code like.

     

    //Using Lambda Expression

    List<int> even1 = arrInt.FindAll( x => x % 2 == 0);

     

    This approach is without using delegate but the way of implementation much clean. In this syntax x => x % 2 == 0 can be changed to (int x) => x % 2 == 0

     

    Namoskar!!!

  • Wriju's BLOG

    Visual Studio Codename Orcas Beta Documentation

    • 0 Comments

    Find MSDN documentation for more information.

    Visual Studio
    Visual Studio Team System

     

    Thanks and enjoy.

     

    Namoskar!!!

  • Wriju's BLOG

    C# 3. Resources

    • 0 Comments

    I found a very nice link on C# 3.0 resources and sharing it for you.

     

    Query Composition using Functional Programming Techniques in C# 3.0 by Eric White

     

    This talks about various aspects of C# 3.0 with details.

     

    Namoskar!!!

     

  • Wriju's BLOG

    C# 3.0 Enhancements: Lambda Expression (more on what)

    • 0 Comments

    Lambda Expression gives us the more concise way of Anonymous Method implementation through functional programming language. Let me share some interesting aspects of Lambda Expression while exploring the C# 3.0 Specification. There it is being clearly described what Lambda Expression is.

     

    (param) => expr

     

    Can be expressed as

     

    param => expr

     

    Couple of the examples are given there

     

    x => x + 1                // Implicitly typed, expression body

    x => { return x + 1; }    // Implicitly typed, statement body

    (int x) => x + 1                // Explicitly typed, expression body

    (int x) => { return x + 1;}// Explicitly typed, statement body

    (x, y) => x * y            // Multiple parameters

    () => Console.WriteLine()  // No parameters

     

    It is very interesting to me. Hope you will also enjoy this.

     

    Namoskar!!!

  • Wriju's BLOG

    Visual Studio Code Name “Orcas” Beta 1 Released

    • 0 Comments

    Go ahead and download from here.

     

    Namoskar!!!

Page 1 of 1 (11 items)