In your example, you are probably best using the following:
MyClass val = myObject as MyClass;
However, to answer your question - yes, the answer is to use generics:
protected T GetAValue<T>(object someObject) { if (someObject is T) { return (T)someObject; } else { // We cannot return null as T may not be nullable // see http://stackoverflow.com/questions/302096/how-can-i-return-null-from-a-generic-method-in-c return default(T); } }
In this method, T is a type parameter. You can use T in your code just like any other type (for example, a string), however, note that in this case we do not restrict T, and therefore objects of type T have properties and methods of the object ( GetType() base , ToString() , etc.)
We must obviously declare what T is before we can use it - for example:
MyClass val = GetAValue<MyClass>(myObject); string strVal = GetAValue<string>(someObject);
See the MSDN documentation for shared files for more information.
Justin
source share