.NET Xpress

Microsoft Technology Xplicit

Archive for the ‘C#’ Category

Language enhancements in C#

Iterators

Posted by anandkumar2004 on January 23, 2007

Iterators allows you to easily create enumerable classes , it’s nothing but  a piece of code that returns an ordered sequence of same type. Its actually implements foreach loop without having implement of entire IEnumerable interface.The class or structure must have a method which returns  IEnumerator or IEnumerable In order to used with foreach construct. The code block of the method must have  the keyword  yield  in context with the keyword return  to retrieve/return a value to the caller. The code block can have  the Keyword  yield  in context with the keyword break to terminate the iteration.Here is the code snippet to demonstrate Iterators

using System;
using System.Collections.Generic;
using System.Text;

namespace IteratorSample
{
    class MyIterator
    {
        public string[] StrName = new string[100];
        public void AddName()
        {
            for (int i = 0; i < 100; i++)
            {
                StrName[i] = i.ToString();
            }
        }
        public System.Collections.IEnumerator GetEnumerator()
        {
            foreach (string str in StrName)
                yield return str;
            //yield is the keyword to use for iterators

        }

        static void Main(string[] args)
        {
              MyIterator obj = new MyIterator();
            obj.AddName();
            foreach (string name1 in obj)
            {
                Console.WriteLine(name1);

            }
            Console.ReadLine();
        }
    }

}

Cheers

Anand

Posted in C# | Leave a Comment »

Anonymous Method

Posted by anandkumar2004 on January 5, 2007

Anonymous method is one of the major enhancements in C# 2.0  its is nothing but a nameless method  used anywhere  a delegate type is expected. It is defined as in-line but not as a member method , the in-line code can use 

1.class member variable
2.local variable defined at the scope of its containing method
3.its own local variable

Below code snippet demonstrate how to use the Anonymous method

using System;

using System.Collections.Generic;

using System.Text;

namespace AnonymousSample

{

class Program {

delegate void MyDelegate(string strName);

public void MySample()

{

Console.WriteLine(” Calling another method”);

}public void MyMethod()

{

MyDelegate del = delegate(string strName){Console.WriteLine(“Hello {0}”, strName);MySample();};del(“UG Members , How Are You ?”);}

static void Main(string[] args)

{

Program pr = new Program();

pr.MyMethod();

Console.Read();}//Anonymous Method with Generics //delegate void MyDelegate<T>(T Item);

//public void MyMethod()//{

// MyDelegate <string> del = delegate(string strName)// {// Console.WriteLine(”Hello {0}”, strName);// //MySample();

// };// del(”Anand”);//}

}

} Note :  Commented code demonstrates how to use anonymous method for generics ,to test  comment code above to
Main(..) method and uncomment the below code

Cheers

Anand

Posted in C# | Leave a Comment »

Lambda Expression

Posted by anandkumar2004 on January 4, 2007

This is a very interesting feature of C# 3.0.This is  more  sophisticated  and  provide more functional programming benefit as compare to  anonymous methods ,anonymous method is one of the major enhancements in C# 2.0  its is nothing but a nameless method  used anywhere  a delegate type is expected .Lambda expression is the advance version of anonymous.

Some basic feature of Lambda expression is it written as a parameter list, followed by the => symbol, for example

(int lambdaExp)  => lambdaExp +1;

This is not hard and fast rule that we must specify the type  in parameter list , if you specify the type then its called as explicit parameter list and  if you do not specify the type then it’s called as implicit parameter list for example

lambdaExp  => lambdaExp +1;

Below code snippet demonstrate  how to use lambda expression , in this example I am trying to display the person name whose length is greater than 4
using System;
using System.Collections.Generic;
using System.Text;
using System.Query;
using System.Xml.XLinq;
using System.Data.DLinq;

namespace lamdaexpression
{
    class Program
    {
        static void Main(string[] args)
        {
            var friendList = new List<string>();
            friendList.Add(“Anand”);
           friendList.Add(“Arun”);
           friendList.Add(“Sudha”);
           friendList.Add(“Anjana”);
            friendList.Add(“Sasi”);
            friendList.Add(“Pratap”);
            friendList.Add(“Jani”);

            var newList = friendList.FindAll( nameLen => nameLen.Length>4);

            foreach (string name in newList)
         {
          Console.WriteLine(name);
         }
            Console.ReadLine();
        }
    }
}
You can specify more then one expression in the parameter list some of the code benefits of Lambda expression are

1. Lambda expression allows explicitly and impiety parameter list  unlike anonymous method expects a explicitly type
2. The implementation  ( body part) of lambda expression can be a piece of code or a  expression .
3. Lambda expressions with an expression body can be converted to expression trees.Expression tree is provide the facility to treat lambda expressions as data .This helps you to implement extension method  ( will discuss about it in my next post ) .

Cheers

Anand

Posted in C# | Leave a Comment »

LINQ – Part 2

Posted by anandkumar2004 on December 28, 2006

Here is the second part of my LINQ article , before to that my previous article has one small error.In various places I have mention form  it’s a typo  the correct word is from   (apology for the typo :-) )

To start my second part  lets look at the sample code , here I am trying to demonstrate  how efficient and quickly we can  play around with collection classes using LINQ .

using System;

using System.Collections.Generic; using System.Text;

using System.Query;using System.Xml.XLinq;

using System.Data.DLinq; namespace QueryExpression{

class Player{

public string PlayerName; public string Country;

public int TotalRuns;public int NoManoftheMatch;

}

 class Program {

public List <Player> PlayerList = new List<Player>();static void Main(string[] args)

{

Program pr = new Program(); pr.AddObj(); var queryOutput = from player in pr.PlayerList

where ( player.TotalRuns>=10000) orderby player.TotalRuns descending

select ( new {player.PlayerName,player.TotalRuns,player.NoManoftheMatch} );foreach( var p in queryOutput)

{

Console.WriteLine(“Name : {0} Runs : {1} Man of the Match (no of times) : {2}”,p.PlayerName,p.TotalRuns,p.NoManoftheMatch); }

 Console.ReadLine();}//adding the player information

 public void AddObj()

{

Player objPlayer1 = new Player{PlayerName= “Sachin”,Country=“Ind”,TotalRuns= 10527 ,NoManoftheMatch=10}; Player objPlayer2 = new Player{PlayerName= “Lara”,Country=“WI”,TotalRuns= 11953,NoManoftheMatch=12};

Player objPlayer3 = new Player{PlayerName= “Ponting”,Country=“AUS”,TotalRuns= 9316,NoManoftheMatch=14};Player objPlayer4 = new Player{PlayerName= “Dravid”,Country=“Ind”,TotalRuns= 9082,NoManoftheMatch=9};

Player objPlayer5 = new Player{PlayerName= “Inzi”,Country=“Pak”,TotalRuns= 8615,NoManoftheMatch=8}; Player objPlayer6 = new Player{PlayerName= “Kallis”,Country=“SA”,TotalRuns= 8072,NoManoftheMatch=16};

Player objPlayer7 = new Player{PlayerName= “Langer”,Country=“Aus”,TotalRuns= 7623,NoManoftheMatch=8};Player objPlayer8 = new Player{PlayerName= “SWaugh”,Country=“Aus”,TotalRuns= 10527,NoManoftheMatch=14};

Player objPlayer9 = new Player{PlayerName= “Gavaskar”,Country=“Ind”,TotalRuns= 10122,NoManoftheMatch=5};

Player objPlayer10 = new Player{PlayerName= “Border”,Country=“Aus”,TotalRuns= 11174,NoManoftheMatch=11};

PlayerList.Add(objPlayer1);

 PlayerList.Add(objPlayer2); PlayerList.Add(objPlayer3);

PlayerList.Add(objPlayer4);

PlayerList.Add(objPlayer5);

PlayerList.Add(objPlayer6);

PlayerList.Add(objPlayer7);

PlayerList.Add(objPlayer8);

PlayerList.Add(objPlayer9);

PlayerList.Add(objPlayer10);

}

}

}

If  you look at the select or where   this is nothing but the extension methods defined in System.Query and new{…}  is nothing anonymous type and object initializer and in foreach loop I have used  implicit typing of local variables , without local variable type its very hard to get the required output because we   may not  know the  possible type of the data returned . LINQ provides lots other options/clauses  such as join, groupby, distinct, union, any, all and  aggregated functions ( sum, count, average, max, min, aggregate)  etc to support structure query language programming model more strongly .I am concluding this session here and  suggest you all top start  explore LINQ .If you have any doubt please feel free to  post your queries  to me – anandkumar2004@gmail.com

Cheers

Anand

Posted in C# | Leave a Comment »

LINQ – Part 1

Posted by anandkumar2004 on December 27, 2006

This article split into 2 part , here is the first part.Query expression  is one of the most interesting and great feature of C# 3.0  , it also know as LINQ (Language INtegrated Query) . This provides the facility to access the .NET objects  or  collection class  data the way we use structure query language to communicate with relational database ( like select, where from etc..) .The main  purpose of LINQ is to bring the .NET programming language model to  SQL programming model platform .Earlier we use C#/VB.NET to interact with .NET framework and  SQL statements to interacts with database the main problem is .NET compiler unable to checking the  query statements embedded in quotes, no type checking of return values and so on but through LINQ its possible now .The other advantages of LINQ is we can filter our collection data the way we want without writing additional loops. The query expression ( LINQ) begins with  from clause and ends with select  clause .Have a look at the example below

using System;using System.Collections.Generic;using System.Text;using System.Query;

using System.Xml.XLinq;using System.Data.DLinq;namespace QueryExpression{class Program{

static void Main(string[] args){ string[] companyNames = { “Microsoft”, “Oracle”, “Motorola”, “Sun”, “Google”, “Borland”, “Sony”,“Nokia”,“Samsung”,“GM” }; var finalResult = from company in companyNames where company.Length > 6select company;

foreach (string CoName in finalResult)Console.WriteLine(CoName);Console.ReadLine(); } }}

In this example I was trying to demonstrate to display the list of companies whose length is great than  6 characters by using query expression. The  from clause generates one or more iteration variables , where clause used to filters the data ( restricted operator )   and  select clause used to capture the  required output .In my next article I will cover few more core features of  LINQ with some example.

Please post your queries on C# 2.0 or C# 3.0 @ anandkumar2004@gmail.com

Cheers

Anand

Posted in C# | Leave a Comment »

Extension Method

Posted by anandkumar2004 on December 22, 2006

Extension method is a very interesting feature of C# 3.0.Extension method  provides the ability to extend  the  functionality of  a existing class or  any existing type by writing a new  static method  and invoked through a normal instance method .Extension method declare through the keyword this as a modifier on the first parameter of the method. The below cod snippet demonstrates a extension method called StrLen(..) which display the string which is more then  4 characters long .

using System;

using System.Collections.Generic;

using System.Text;

using System.Query;

using System.Xml.XLinq;

using System.Data.DLinq;

namespace Extension_Method

{

public static class Extensions

{

public static void StrLen(this string friendsName)

{

if (friendsName.Length>4)

Console.WriteLine(friendsName);

}

}

class Program

{

static void Main(string[] args)

{

string[] friendsName = new string []{“Anand”,“Sasi”, “Sudha” , “Arun”, “Anjana”};

foreach (string strName in friendsName)

friendsName.StrLen(strName);

Console.ReadLine();

}

}

}

Extension method is very much useful in some certain situation  like you want to extent the functionality  a class or type belongs to a  3rd party library  in your project and the library does not expose the necessary class or interface , through extension method you can enhance the required functionalities .

Please post me your queries on C# 3.0  @ anandkumar2004@gmail.com

Posted in C# | Leave a Comment »

Object Initializer in C# 3.0

Posted by anandkumar2004 on December 14, 2006

Object initializer is  a new language enhancements of C# 3.0.This helps to initialize the initial value  to the specified data member(s)  of the newly created object or collection in a single step  , {} braces used to initialize the data members  as below
using System;

using System.Collections.Generic;

using System.Text;

using System.Query;

using System.Xml.XLinq;

using System.Data.DLinq;

namespace Object_Initializers

{

class Employee

{

public int EmpNo;

public string EmpName;

static void Main(string[] args)

{

Employee empObj = new Employee{EmpNo = 1,EmpName=“Anand”};

Console.WriteLine(“The Emp No # {0} Emp Name # {1}”,empObj.EmpNo,empObj.EmpName);

Console.ReadLine();

}

}

}

 
This is equals to invoke  a instance constructor and   assign value to each field . Each member initializer assigns a value to a field or property of the object . the object initialize applicable to collection class as well .The process of initialize the collection object is similar to the above code .

List<string> listObj = new List<string> {“UG Hyderabad”,“UG Bangalore”,“UG Chennai”,“UG Mumbai”};

foreach ( string s in listOobj)

Console.WriteLine(s);

Few  points you must keep in mind while using the object initializer 

 1. The Member initializer must be a field or property (set property)  of the object
 2. You can not initialize multiple values to the same field or property
 3. The initializer applies to the collection of type  System.Collections.Generic.ICollection<T>

Cheers

Anand

Posted in C# | Leave a Comment »

Implicity Typed Local Variable

Posted by anandkumar2004 on December 12, 2006

Implicitly typed local variable provides the facility to declare the variable  without specify the type , compiler will  implicitly declare the type of the variable based on the value  initialize .To declare the local variable use the keyword called var   for example

  var name= “Hello MUGH”;

// this is equals to

string  name = “Hello MUGH”;

//define a generic type

var myList = new List<int>();

myList.Add(100); 

Implicitly local variable makes our job very easy but it work with few constraints like

·        Implicitly type declaration must have initialize to a value

                             // value must initialize

var x;  // it’s a compile time error

·        The initializer expression cannot be the null type

var x = null;

·        The initializer cannot be an object or collection initializer by itself, but it can be a new expression that includes an object or collection initializer.

                          // collection initializer not allowed

                               var x = { 1, 2, 3}; 

                               // it can be declare as

                            var numbers = new int[] {  1, 2, 3};

Posted in C# | Leave a Comment »

C# Orcas

Posted by anandkumar2004 on December 8, 2006

Hi Dear reader ,

I am starting a series of articles on the new enhancements in  C# 3.0 .Please watch this space

Cheers

Anand

Posted in C# | Leave a Comment »

About Nullable Types

Posted by anandkumar2004 on December 7, 2006

Nullable types gives you the ability to create types that can hold unknown (null)  values .
 
Code Sample
==========
System.Nullable<int>  nullVal;
nullVal = null; // assign some value
//quicker  way of doing is
int? nullVal = null; // assign some other value
 
The take away points of Nullable types are
 
• The syntax T? is shorthand for System.Nullable<T> structure , where T is a value type.
• Leverage HasValue and Value( both are read-only member) to test for null and retrieve the value.
• Use the ?? operator to assign a default value if the value is null
        Ex: int? x = null; int y = x ?? 100; // assign default value
 
• Nested nullable types are not allowed

Posted in C# | Leave a Comment »