Reputation: 181
We have a generic class called Context<T> where T : class
, and create another class Message
to be used together with the previous one as Context<Message>
.
Generally speaking, we are wondering if there is a way to convert a Context<object>
back to Context<Message>
.
We can do a check that the object is of type Message,
but doing Context<Message> context = (Context<Message>) otherContext;
where otherContext is Context<object>
Is this possible in some way?
Upvotes: 0
Views: 144
Reputation: 10035
If you prefer cast, try this:
class YourClass<T> where T : class
{
public static implicit operator YourClass<T>(YourClass<object> instance)
{
// Create YourClass<T> from YourClass<object>
// e.g. return new YourClass<T>(...)
}
}
var obj = new YourClass<object>();
YourClass<Message> msg = obj;
Otherwise, you could create a constructor:
class YourClass<T> where T : class
{
public YourClass(YourClass<object> obj)
{
}
}
Or you can have both.
Upvotes: 2