Sunday, August 31, 2008

.Net Generics and Value Data Type

I use .Net Generics a lot. The great benefit is that you can make your codes reusable even you may use it only for one data type. You may extract the generic class or method to a library to a library for reuse. Secondly, it still keeps type safe or strong type integrity. Any attempts to use wrong type will be caught at compile time instead of run time.

The generics can be specified by where clause. In most cases I use generics for reference data types, i.e., classes. If you say a generic as class, that means the generics data type is a reference type. You can use new() to further indicate the class can be instantiated by the default constructor with no parameters. If you specify the class a specified class, that means any class which inherits from the class can be used for the generics class or method.

You cannot use more than one classes in where clause, however, you can use interfaces to specify that the generic class should implement some interfaces. Then in your generic class or method, you can safely call the implemented interfaces or methods.

How about value data types such as int, string or double as examples. You can use struct in the where clause. If you want to use the nullable value data types, you can simply use ? after the generic type, such as T?.

class Test
{
public T GetValueOrDefault<T>(T? item)
where T: struct
{
return item.GetValueOrDefault();
}
public T? GetValue<T>(T? item)
where T: struct
{
if (item.HasValue)
{
return item.Value;
}
else
{
return null;
}
}
}


here are codes to call the methods:

Test t = new Test();
int? a = 2;
a = t.GetValueOrDefault<int>(a);
//t.GetValueOrDefault<Test>(t); //Error: t is not none-nullable data type
Console.WriteLine("GetValueOrDefault<int>(a) = {0}; GetValue<int>(a) = {1}",
t.GetValueOrDefault<int>(a), t.GetValue<int>(a));
a = null;
Console.WriteLine("GetValueOrDefault<int>(a) = {0}; GetValue<int>(a) = {1}",
t.GetValueOrDefault<int>(a), t.GetValue<int>(a));
Console.WriteLine("GetValueOrDefault<int>(a) = {0}; GetValue<int>(a) = {1}",
t.GetValueOrDefault<int>(3), t.GetValue<int>(3));
 


The result of the above codes in a console is:



Here is an interest posting on .Net Generics and a question about enum data type.

0 comments: