first_page the funky knowledge base
personal notes from way, _way_ back and maybe today

“An Introduction to C# Generics”; Juval Lowy on Casting Generic Types and the Use of as and is Operators

The C# compiler only lets you implicitly cast generic type parameters to Object, or to constraint-specified types, as shown [below]. Such implicit casting is type safe because any incompatibility is discovered at compile-time.

…Implicit casting of generic type parameters

interface ISomeInterface {...} class BaseClass {...} class MyClass<T> where T : BaseClass,ISomeInterface { void SomeMethod(T t) { ISomeInterface obj1 = t; BaseClass obj2 = t; object obj3 = t; } }

The compiler lets you explicitly cast generic type parameters to any other interface, but not to a class:

interface ISomeInterface {...} class SomeClass {...} class MyClass<T> { void SomeMethod(T t) { ISomeInterface obj1 = (ISomeInterface)t;//Compiles SomeClass obj2 = (SomeClass)t; //Does not compile } }

However, you can force a cast from a generic type parameter to any other type using a temporary Object variable:

class SomeClass {...}

class MyClass<T> { void SomeMethod(T t) { object temp = t; SomeClass obj = (SomeClass)temp; } }

Needless to say, such explicit casting is dangerous because it may throw an exception at run time if the type argument used instead of the generic type parameter does not derive from the type to which you explicitly cast. Instead of risking a casting exception, a better approach is to use the is and as operators, as shown [below]. The is operator returns true if the generic type parameter is of the queried type, and as will perform a cast if the types are compatible, and will return null otherwise. You can use is and as on both generic type parameters and on generic classes with specific type arguments.

…Using 'is' and 'as' operators on generic type parameters

public class MyClass<T> { public void SomeMethod(T t) { if(t is int) {...}

   if(t is LinkedList&lt;int,string&gt;)
   {...}

   string str = t as string;
   if(str != null)
   {...}

   LinkedList&lt;int,string&gt; list = t as LinkedList&lt;int,string&gt;;
   if(list != null)
   {...}
}

}

[http://msdn.microsoft.com/en-us/library/ms379564(VS.80).aspx]

mod date: 2009-07-19T17:29:12.000Z