C# generics: reference type vs. value

Posted by Sksingh under C# category on | Points: 40 | Views : 3404
Generics are the most powerful feature of C# 2.0. It allows defining type-safe data structures, without committing to actual data types. But in most of the application we come across situation where we need type that can hold both reference & value type. In such cases we need only either value type or reference type.

For example:

List<int> list = new List<int>();
list.Add("hello"); // compiler error!

As we know List is inbuild generic collection that can have value type as well ref type based on the it will validate its data.
In above example compilation error throwing reason that List initialized with int type ie. value type.

Now question how to create either value type or reference type custom generic that enforce validation at intialize time itself.


class Employee <T> where T: class
{ }
class OnlyNumber <T> where T: struct { }

From a above Employee class is ref type generic that can have only reference data type .
and OnlyNumber class where T points to struct can have only number that means only value type.

Comments or Responses

Posted by: Akiii on: 6/6/2011 Level:Bronze | Status: [Member] | Points: 10
Hi Sunil,

Please can you explain the ref types and value type...?
I didnt understand...!

Any help is appreciated..
Thanks and Regards

Posted by: Sksingh on: 6/6/2011 Level:Starter | Status: [Member] | Points: 10
Hi Akiii,

For your information List<T> is a generic type collection where T will be anything ie, string, int etc.

But some scenario we need to restrict to some type either value type or reftype.

For Example : If List is customize List that can have value type only then below code would not work.

List<string> str =new List<string> 


List<int> intValue =new List<int> 

will work perfectly.

Hope its clear...
If you need more descriptive then i will send you complete code.
Posted by: Akiii on: 6/6/2011 Level:Bronze | Status: [Member] | Points: 10
hi sunil...
thank you for your reply.....
I read your code, i have understood a little......

Please provide me the code if possible......

Thanks and regards

Login to post response