C# 2.0 to C# 4.0 - Key Features


This article is about some of the features of C# (.Net 2.0 to .Net 4.0). It provides introduction for various useful topics such as Business Entities, Object Initializers, Interface, Using Generics, IDictionary and IEnumerator Interfaces, GetEnumerator() and yield keyword along with code snippets to understand that topics.

Environment used : Visual Studio 2010, .Net 4.0

Summary:

1. Entity class :

- An entity is something that can hold a set of data related for subsequent use in the same application.
- It can be Employee entity, Payroll entity, Member entity and so one.
- Technically, an entity is a simple class that has some members including some data state and code logic.
E.g. EmployeeId, EmployeeName, EmployeeDepartmentId, EmployeeLocationDetail and so on.

In the "FINAL CODE", notice 2 entity classes; Member and Product.

2. Initializer :

- Incorporated in C# 3.0 to provide simple way to initialize entity members at the time of instentiation.

Some of the initializers are...

Object Initializer...

a. C# 2.0 way (large code)



// creating 4 objs of Member class, initialize them & add them in a collection

MyCollection members = new MyCollection();

Member member;

// create 1st member's object
member = new Member();
member.MemberId = 1;
member.MemberName = "Sharad";
member.Skills = "Java";
member.Add(member);

// create 2nd member's object
member = new Member();
member.MemberId = 1;
member.MemberName = "Sharad";
member.Skills = "Java";
member.Add(member);

// create 3rd member's object
member = new Member();
member.MemberId = 1;
member.MemberName = "Sharad";
member.Skills = "Java";
member.Add(member);

// create 4th member's object
member = new Member();
member.MemberId = 1;
member.MemberName = "Sharad";
member.Skills = "Java";
member.Add(member);



b. C# 3.0 way (using object initializer)


MyCollection members = new MyCollection();

members.Add(1, new Member() { MemberId = 1, MemberName = "Sharad", Skills = "Java" });
members.Add(2, new Member() { MemberId = 2, MemberName = "Rakesh", Skills = "Unix" });
members.Add(3, new Member() { MemberId = 3, MemberName = "Rajeev", Skills = "Dotnet" });
members.Add(4, new Member() { MemberId = 4, MemberName = "Rizwan", Skills = "Oracle" });



List Initializer...

- In the same way we can initialize a List the moment we instantiate its object...

a. C# 2.0 way..(large code)


List lst = new List();
lst.Add("item-1");
lst.Add("item-2");
lst.Add("item-3");
lst.Add("item-4");
lst.Add("item-5");



b. C# 3.0 way...(easy code)


List lst = new List { "item-1", "item-2", "item-3", "item-4", "item-5" };



Dictionary Initializer...

- In the same way we can initialize Dictionary object with less efforts...

a. C# 2.0 way...(large code)


Dictionary dict = new Dictionary();
dict.Add(100, "Item-1");
dict.Add(200, "Item-2");
dict.Add(300, "Item-3");
dict.Add(400, "Item-4");



b. C# 3.0 way ...(easy code)



Dictionary dict = new Dictionary { { 100, "Item-1" }, { 200, "Item-2" }, { 300, "Item-3" }, { 400, "Item-4" } };



- Hence initializers provide a simple way to initialize objects at the time of their creation.

In the "FINAL CODE", notice initializers used to initialize members and products collections.

3. Interface :

- You must be knowing this features already
- Just brushing-up it again.... Interface is a contract that should be followed by implementer class to achieve specific objectives.
- It has only signatures of methods whereas the actual implementations have to be provided in the class that uses this interface.
- In following code I have created interface ICollectionBase.

4. Generics :

- This feature was introduced in C# 2.0 and changed the overall programing style because of some of its salient features.
- For more information on this topic please refer my article "Generics Simplified (C#)" at...

http://www.dotnetspider.com/resources/37561-Generics-Simplified.aspx

5. IDictionary :

- IDictionaly interface is a "way of representing" collection of key and value pairs.
- Whereas Dictionaly is the hash table of key, value pairs in which values can keep individual
instances of data (typically business entities) and keys are their unique identities.

In the FINAL CODE SNIPET, refer this part...



// object container
IDictionary dict = new Dictionary();



6. IEnumerator :

- IEnumerator provides the representation for some methods like; MoveNext, Curent and Reset.
- Whereas IEnumerable interafce provides GetEnumerator() method that lets a collection become enumerable.

In the "FINAL CODE", notice following code...



// or return collection through getEnumerator and yield
public IEnumerator GetEnumerator()
{
foreach (INFO info in dict.Values)
{
...
}
}



7. GetEnumerator():

- This method works as access point that lets user class iterate individual objects of the current collection.
- GetEnumerator() method returns IEnumerator.

In the "FINAL CODE", notice following code...



// or return collection through getEnumerator and yield
public IEnumerator GetEnumerator()
{
....
}




8. yield keyword :

- This keyword works as a delayed data provider that returns either IEnumerable or IEnumerator interfaces to the user.
- Whenever it occures in the flow, it returns the next available object of the collection.



In the "FINAL CODE", notice following code...



// or return collection through getEnumerator and yield
public IEnumerator GetEnumerator()
{
foreach (INFO info in dict.Values)
{
yield return info;
}
}



- In this snippet yield returns INFO object as IEnumerator and in next call this will return next object... and so on.
- Want to know more about yield return and yield break? refer a good article on...

http://iserialized.com/a-quick-start-guide-to-yield-return-and-yield-break/


FINAL CODE


- Create a simple console application with the following code and run it.



using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
#region example with Member class

Console.WriteLine("\nExample for Member class.....................");

// instentiating custom collection class
MyCollection members = new MyCollection();

// Adding object in collection
members.Add(1, new Member() { MemberId = 1, MemberName = "Sharad", Skills = "Java" });
members.Add(2, new Member() { MemberId = 2, MemberName = "Rakesh", Skills = "Unix" });
members.Add(3, new Member() { MemberId = 3, MemberName = "Rajeev", Skills = "Dotnet" });
members.Add(4, new Member() { MemberId = 4, MemberName = "Rizwan", Skills = "Oracle" });

// Removing object from collection
members.Remove(1);

// Return a Member object from the collection
Member member = members.ReturnINFO(2);

Console.WriteLine("Return member collection through ``collection class's method''....");
foreach (Member m in members.ReturnINFOCollection().Values)
{
Console.WriteLine(m.MemberId.ToString() + " " + m.MemberName + " " + m.Skills);
}

Console.WriteLine("\nReturn member collection through ``collection class's property''....");
foreach (Member m in members.INFOCollectionProperty.Values)
{
Console.WriteLine(m.MemberId.ToString() + " " + m.MemberName + " " + m.Skills);
}

Console.WriteLine("\nReturn member collection through ``collection object directly''....");
// this is possible by using GetEnumerator() method in the collection class. If we comment GetEnumerator() method in collection class and compile,
// we receive error ".... MyCollection does not implement public definition of GetEnumerator..."
foreach (Member m in members)
{
Console.WriteLine(m.MemberId.ToString() + " " + m.MemberName + " " + m.Skills);
}

#endregion

#region example for Product class using the same generic collection as that of Member

Console.WriteLine("\nExample for Product class.................");

// instentiating custom collection class
MyCollection products = new MyCollection();

// Adding object in collection -- Initializers
products.Add(1, new Product() { ProductId = 100, ProductName = "Orale ", Price = 10000 });
products.Add(2, new Product() { ProductId = 101, ProductName = "Windows ", Price = 15000 });
products.Add(3, new Product() { ProductId = 102, ProductName = "VS2010 ", Price = 7000 });
products.Add(4, new Product() { ProductId = 103, ProductName = "Sql2010 ", Price = 6000 });

// Removing object from collection
products.Remove(2);

// Return a Member object from the collection
Product product = products.ReturnINFO(1);

Console.WriteLine("Return product collection through ``collection class's method''....");
foreach (Product p in products.ReturnINFOCollection().Values)
{
Console.WriteLine(p.ProductId.ToString() + " " + p.ProductName + " " + p.Price.ToString());
}

Console.WriteLine("\nReturn product collection through ``collection class's property''....");
foreach (Product p in products.INFOCollectionProperty.Values)
{
Console.WriteLine(p.ProductId.ToString() + " " + p.ProductName + " " + p.Price.ToString());
}

Console.WriteLine("\nReturn product collection through ``collection object directly''....");
// this is possible by using GetEnumerator() method in the collection class. If we comment GetEnumerator() method in collection class and compile,
// we receive error ".... MyCollection does not implement public definition of GetEnumerator..."
foreach (Product p in products)
{
Console.WriteLine(p.ProductId.ToString() + " " + p.ProductName + " " + p.Price.ToString());
}

#endregion

Console.ReadKey();
}
}

#region BUSINESS ENTITIES

// one business entity
public class Member
{
public int MemberId { get; set; }
public string MemberName { get; set; }
public string Skills { get; set; }
}

// another busines entity
public class Product
{
public int ProductId { get; set; }
public string ProductName { get; set; }
public int Price { get; set; }
}

#endregion

# region INTERFACE

// interface
public interface ICollectionBase
{
bool Add(int a, INFO b); // method
bool Remove(int a); // method
INFO ReturnINFO(int a); // method
IDictionary ReturnINFOCollection(); // method
// IDictionary INFOCollectionProperty; // property - not allowed in interface ;)
}

#endregion

#region GENERIC COLELCTION CLASS

// Generic based collection class that implements generic based interface for runtime support to our Business entities by generic type
public class MyCollection : ICollectionBase where INFO : new()
{

// object container
Dictionary dict = new Dictionary();

// add an object to container
public bool Add(int hashCode, INFO info)
{
if (dict.ContainsKey(hashCode))
{
return false;
}
dict.Add(hashCode, info);
return true;
}

// del an object in container
public bool Remove(int hashCode)
{
if (!dict.ContainsKey(hashCode))
{
return false;
}
dict.Remove(hashCode);
return true;
}

// return an object from container based on its key
public INFO ReturnINFO(int hashCode)
{
if (!dict.ContainsKey(hashCode))
{
return default(INFO);
}
return dict[hashCode];
}

// return collection through a method
public IDictionary ReturnINFOCollection()
{
return dict;
}

// or return collection through a property
public IDictionary INFOCollectionProperty
{
get
{
return dict;
}
}

// or return collection through getEnumerator and yield
public IEnumerator GetEnumerator()
{
foreach (INFO info in dict.Values)
{
yield return info;
}
}
}

#endregion

}



Save and Run it.

Hope you find this resource useful.

Please drop a query incase you want more information for any of the features used in this snippet.

Thanks
Sharad


Comments

Author: PalaniKumar.A05 Apr 2011 Member Level: Gold   Points : 1

hi,

It is very nice explanation about Visual Studio 2010, .Net 4.0.

and good example in IEnumerator, GetEnumerator() etc..



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: