I have a simple class, which looks something like this:
public class MyClass<T>
{
public int Status { get; set; }
public T Value { get; set; }
}
For convenience, I have another class which inherits from MyClass<string>
, to allow me to construct MyClass
without generic arguments, such as:
public class MyClass : MyClass<string> { }
I want to be able to cast MyClass<T>
to MyClass
, and it seems this doesnt work by default. This example cast throws the following error:
MyClass<string> withT = new MyClass<string> { Status = 1, Value = "Somevalue" };
MyClass withoutT = (MyClass)withT;
Unable to cast object of type 'MyClass`1[System.String]' to 'MyClass'
So I believe I need to implement some implicit/explicit casting logic, as described in this answer.
I've updated MyClass<T>
as follows, however the same error is still thrown:
public class MyClass<T>
{
public int Status { get; set; }
public T Value;
public static implicit operator MyClass(MyClass<T> myClass)
{
return new MyClass
{
Status = myClass.Status,
Value = myClass.Value.GetType() == typeof(string) ? myClass.Value.ToString() : null
};
}
}
Can anyone help point out where I'm going wrong?