I know this is an old thread but all answers posted so far have not directly addressed this question and instead only suggested workarounds (i.e. "use reflection", "make your DoSomething()
method generic" or "create a non-generic base class and call this base class' method").
Can I even make a cast without specifying the generic type of the class?
So to clearly answer your question: No it is not possible. Due to the covariance constraints in C# you cannot cast into a generic class.
In more detail: I am assuming you would want to use x as Home<object>
as the lowest common denomitator in order to be be able to call toString()
provided by the Object
class. Casting your object x
to Home<object>
would require covariance which is not possible with classes (only generic interfaces and delegates can be covariant). while this is great to prevent mistakes at compile time, it is certainly an annoyance when wanting to access methods on generic classes, as in your case. @n8wrl answer is probably your best shot in terms of "casting".
That being said, you could also go for an interface-based solution, using the out flag on your T parameter:
interface IHome<out T> {
string GetClassType { get; }
}
public class Home<T> : IHome<T> where T : class
{
public string GetClassType
{
get { return typeof(T).Name; }
}
}
Then this should work:
public void DoSomething(object x)
{
if(x is // Check if Home<>)
{
var y = x as IHome<object>;
var z = y.GetClassType;
}
}