Graviton Graviton - 3 years ago 74
C# Question

Cast from Generics<T> to Specific SubClass

I have a class as such

public class MyClass<T> where T : OneType
{
T MyObj { get; set; }

public MyCLass(T obj)
{
}
}

public class SubClass: MyClass<TwoType>
{
}

// snip for other similar class definition


where,
TwoType
is derived from
OneType
.

Now, I have this utility method

public static MyClass<T> Factory<T>(T vd)
where T : OneType
{
switch(vd.TypeName)
{
case Constant.TwoType
return new SubClass((TwoType)vd);
// snip for other type check
}
}


Which function is, obviously, checks the type of
vd
, and the creates an appropriate
MyClass
type. The only problem is the above code won't compile, and I don't know why

The error is


Cannot cast expression of T to TwoType

Answer Source

Amazing, I got it working by writing the code as such:

return (new SubClass(vd as TwoType) as MyClass<T>);

or

return (MyClass<T>)(object)new SubClass((TwoType)(object)vd );

But,

return (MyClass<T>)new SubClass((TwoType)vd );

doesn't work.

There seems to be a difference in as and () casting.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download