Friday, March 21, 2008

Use of Generics with C#

Its a long time when I last posted...

Now I am coming up with a brief but self explanatory article on C# Generics that will explain use of generics to less experienced persons in C#.

Before continuing to this post I would like to say if you are not using the concept of objects and classes (or say OOPS principles) in your development than the principle of Generics is not going to help you much.

However, what are Generics?

In a lot of articles you will get the Generics are similar to C++ Templates. Yes it is. The concept is same as C++ Templates but the internal implementation and advantage is the place where both of these differs slightly.

Basically Generics is to do once and use multiple concept.

Now we will write a simple example to let you know about the Generic functions:

Say we want to write a function where we will pass any object:

The function definition will look like this:

public string GetStringRepresentation(T t, string propertyNameToLookFor) where T : new()

{

return "";

}

Now here we are declaring that our first parameter T t is a generic Type.

Now what we can do with this. To use this lets take a look on to the enhanced function below:

public string GetStringRepresentation(T t, string propertyNameToLookFor) where T : new()

{

t = default(T); // specifying the default value to the coming type

return t.ToString();

}

Role of default keyword in generics:

The default keyword let us specify the initial value for the coming type if it is int the default value will go to 0, if the coming type is string it will be assigned to “” or if it is an object the default value will go to null.

For more information follow the link.


Putting constraints on the coming T types in a function:

Suppose you want to put some constraints on the parameter T so that you can look for

using System;

using System.Collections.Generic;

using System.Text;

using System.Reflection;

namespace GenericTest

{

public interface IConstraint

{

void Constraints();

}

public class DummyClass : IConstraint

{

#region IConstraint Members

public void Constraints()

{

// Constraint Applied

}

#endregion

}

public class TypeTProceesing

{

public T ProcessT() where T : IConstraint, new()

{

T t = new T();

t.Constraints(); // As we are putting constraint on the

// parameter T that it will be

// implementing interface IConstraint

// That's why we are able to call the

// function Constraints() here.

return t;

}

}

}

If you have any query regarding how to utilize the concepts of Generics

Let me know as a reply for this post or contact me at

Shashank.abes@gmail.com