Linq & C#

Posted on July 31, 2008. Filed under: Language features | Tags: , , , |

C# & LINQ Features

Instantiation
you dont need to create a object variable and assign the instantiation to it.

Example
new MyClass().AddMethod(12,35) ;

Extensions
Declare a Class and add Static class with Extensions keyword under the same namespace
that will add all methods of Static class Extensions to all classes in that namespace

Example

class Class1
{
    public  Class1()
    {

    }
   public void Method1(string s)
   {
    Console.WriteLine(“Class2.Method1″);
   }
}
static class Extensions
{
  static public void Method1(this object o, int i)
  {
    Console.WriteLine(“Extensions.Method1″);
  }

  static void Main()
  {
    new Class1().Method1(12);   // Extensions.Method1 is called
    new Class1().Method1(“12″); // Class1.Method1 is called
  }
}

Caveats

the Method invocation works is decided at runtime with signature of each functoin call, meaning should it invoke class method or static method
Offcourse the precedence is always the class method not the static method when you have the same signature

Conclusion
this is simlar to polymorphism (Overrides and override), but there it is constraint to only one class here it is global to the namespace

Var keyword
the var keyword comes from the JS Scripting language and i love using it
My programming was built on foundation of VB and continuing with VB.NET, a guy like me likes that “option sctrict off”
where it allows you to declare generic Object like System.Object

but it is also available in C# and where it used to give complilation error if you declare object variable

Example
 var processes = new List<ProcessData>();

recomendations
I recommend you to use it with a type not anonymous like
 var processes = new List<of T>();

nevermind i may be wrong, but at the end the compiler creates the code for you and makes your life easy

ObjectInitializer
All these past years of my programming i hated writing many constructers for each possiblity

looked the old way doing things
static class LanguageFeatures
{
  class ProcessData
  {
    public Int32 Id { get; set; }
    public Int64 Memory { get; set; }
    public String Name { get; set; }
  }
  static void Main(string[] args)
  {
    ProcessData processes = new ProcessData();
    processes.Id =”1″;  
    processes.Name =”devenv.exe”;  
    processes.Memory =”7123456″; 
  }
}

New way of rewriting the code
static class LanguageFeatures
{
  class ProcessData
  {
    public Int32 Id { get; set; }
    public Int64 Memory { get; set; }
    public String Name { get; set; }
  }
  static void Main(string[] args)
  {
    ProcessData processes = new ProcessData(Id=”1″,Name=”devenv.exe”,Memory =”7123456″);
  }
}

Conclusion
it reduces the lines of code and you dont have to deal with parameterised constructors

 

Anonymous Types
when you think about Types, you could think of int, string and more
if you want to create data collection class,all you get in your mind is property methods key value pair and for individual class and its members

I am really tired of creating classes with property methods.
i found this really cool feature of anonymous types

new { process.Id, Name=process.ProcessName,
          Memory=process.WorkingSet64 }
the line would create a class of type unknown classname with properties {id,Name,memory}

Example if wanted to write in legacy style
class Employee {
    private string _FirstName;
    public string FirstName {
        get
        {
            return _FirstName;
        }

        set
        {
            _FirstName = value;
        }
    }

    private string _LastName;
    public string LastName
    {
        get
        {
            return _LastName;
        }

        set
        {
            _LastName = value;
        }
    }
    private string _DeptName;
    public string DeptName
    {
        get
        {
            return _DeptName;
        }

        set
        {
            _DeptName = value;
        }
    }
}

Collection Class
Class Employees :
                    CollectionBase
    {
        public void Add(Employee empObject)
        {
            InnerList.Add(empObject);
        }

        public void Remove(int index)
        {
            InnerList.RemoveAt(index);
        }
        public Employee Item(int index)
        {
            return (Employee)InnerList[index];
        }
       
    } //end of Employees class

Employees emplys = new Employees()

The New Generation Code using C# Anonymous types
var Employees = new List<Object>();
Employees.Add( new {FirstName=”",LastName=”",DeptName=”"});

Conclusion
offcourse when you start comparing both the old style and new style
the main thing you could see is in the previous one they are predefined one where as the new types late binded
the biggest help for the programmers is the number of lines of code

Anonymous Methods
This is a another anonymous featue, which i have never seen.

this feature is mostly usefull in areas where you use delegates or function pointer

here you will be passing the function implementation code as parameter, but the function will be
executed, when it is invoked

here is a sample Example
  static void DisplayProcesses(Func<Process, Boolean> match)
  {
    var processes = new List<Object>();
    foreach (var process in Process.GetProcesses())
    {
      if (match(process))
      {
        processes.Add( new { process.Id, Name=process.ProcessName,
          Memory=process.WorkingSet64 } );
      }
    }

    ObjectDumper.Write(processes);
  }

  static void Main(string[] args)
  {
    DisplayProcesses(process => process.WorkingSet64 >= 20 * 1024 * 1024);
  }

in the above example method DisplayProcesses, is accepting function implementation for expression oriented
and returns boolean data type.
another example is creating function on fly
Example:
myClass1.MyEvent += delegate(string message)

{

    Console.WriteLine(“your message is: {0}”, message);

};

Shadow and override

shadowing hides the inherited methods from base class,
overriding will override the body implmentation not the signature of the base class
so, if you want to override the signature and body implementation then you have to use “new” keyword

Example

public class InternationalShoppingList : ShoppingList
{
    private ArrayList listShopping;

    public ShoppingList() : base()
    {
        listShopping = new ArrayList();
    }

public new InternationalItem[] Items
{
        get
        {
            InternationalItem[] items = new InternationalItem[listShopping.Count];
            listShopping.CopyTo(items);
            return items;
        }
        set
        {
            if (value == null) return;
            InternationalItem[] items = (InternationalItem[])value;
            listShopping.Clear();
            foreach (InternationalItem item in items)
                listShopping.Add(item);
        }
    }

}

// Items in the shopping list
public class InternationalItem : Item
{
    private string _country;
    public string Country
    {
        get { return _country; }
        set { _country = value; }
    }
}

public class ShoppingList
{
    private ArrayList listShopping;

    public ShoppingList()
    {
        listShopping = new ArrayList();
    }

[XmlElement("item")]
public Item[] Items
    {
        get
        {
            Item[] items = new Item[listShopping.Count];
            listShopping.CopyTo(items);
            return items;
        }
        set
        {
            if (value == null) return;
            Item[] items = (Item[])value;
            listShopping.Clear();
            foreach (Item item in items)
                listShopping.Add(item);
        }
    }

}

// Items in the shopping list
public class Item
{
    private string _name;
    public string name
    {
        get { return _name; }
        set { _name = value; }
    }
    public double price;

    public Item()
    {
    }
    public Item(string Name, double Price)
    {
        _name = Name;
        price = Price;
    }
}

Make a Comment

Make a Comment: ( None so far )

blockquote and a tags work here.

Liked it here?
Why not try sites on the blogroll...