| « Article on Tech Head Brothers | Php for Visual Studio (Php4VS) » |
Generics in C#
Generics in C#
Have you already used generics in C# ? Yes ? Then you may already have struggled with the issues I'm going to talk about.
When you are in a generic method, you may want to cast your generic object into another type to do some specific treatment :
class Program
{
static void Main(string[] args)
{
GenericMethod<Class1>(new Class1());
}
static T GenericMethod<T>(T item)
{
Class1 c1 = ((Class1)item);
return item;
}
}
However when you do this, you have the compiler that says you "cannot convert type 'T' to 'Class1'". The tip is to use the as keyword, and the compiler wont bore you anymore :
class Program
{
static void Main(string[] args)
{
GenericMethod<Class1>(new Class1());
}
static T GenericMethod<T>(T item)
{
Class1 c1 = item as Class1;
return item;
}
}
One more thing really useful : when you want to use generic methods, you do not necessarly need to specify the generic type. If the method expect this generic type as parameter, the compiler can infer it :
class Program { static void Main(string[] args) { GenericMethod(new Class1()); } static T GenericMethod<T>(T item) { Class1 c1 = item as Class1; return item; } }
Hope it was useful. Have fun, and keep your little fingers brawny.
8 comments
static T GenericMethod(T item) where T : Class1
{
}In this case, there should be no need to cast to Class1 because item is a Class1.
c1 = (Class1)item; will throw if item is not Class1 whereas c1 = item as Class1; will not, so you have to test for null.Another Try
c1 = (Class1)(object)item; To answer to your remark Fabrice, you're right, but what can I have 2 methods with the same signature but not the same constraint on type ?
public void MyFunction(T item) where T : class
{
if(item.GetType() == typeof(MyClass))
{
// call another method
}
}
However, I fail to see why you would do a cast in a generic function, the whole point of generics is to avoid casting.
Do you have a specific scenario in mind?
Therefore, you'll have :
public void MyFunction(T item) where T : class
{
//I favour the is keyword to have more flexsibility than testing type itself
if(item is MyInterface)
{
//Do action in this case
}
//Do action for item anyway
}
Therefore, someone using that class will need to know the internals to understand what's going on precisely, which breaks a few best practices.
It doesn't seem to me that it's a good usage of generics which, by definition, are supposed to be generics :-).
Comments are closed for this post.