I have a generic function like this:
private LOCAL_TYPE RemoteToLocal<LOCAL_TYPE>(RemoteObjectBaseType remoteObject)
where LOCAL_TYPE: EntityBase
{
Type t = typeof(LOCAL_TYPE);
if (t == typeof(FavoritePlace))
{
return new FavoritePlace(remoteObject as RemotePlaceType1);
}
}
Where EntityBase is non-abstract class. FavoritePlace class is inherited from EntityBase.
However, I’m getting an error:
Cannot implicitly convert type Common.Model.FavoritePlace to ‘LOCAL_TYPE’.
That makes me wonder: FavoritePlace is a child of EntityBase, and LOCAL_TYPE is constrained to be of type EntityBase. Why cannot the conversion happen? I’m probably missing something important here.
EDIT: Okay, based on current answers and some experiment I’ve found another workaround, which is to do following conversion:
if (t == typeof(FavoritePlace))
{
return (LOCAL_TYPE)(EntityBase)new FavoritePlace(remoteObject);
}
Now compiler is happy. But I’m just wondering, if such conversion is possible from compiler’s perspective, why direct conversion to LOCAL_TYPE is not? Isn’t is convertible to relationship transitive?
Although you have established through run-time code that
LOCAL_TYPEis in factFavoritePlace, the compiler does not have the same knowledge statically. The compiler expects you to return an object of typeLOCAL_TYPE, matching exactly the type parameter of the method.Thinks of this situation: someone makes the following call –
Now you’re inside
RemoteToLocal, you go through some conditions, and now it’s time to return the result. You callYou know that this branch in code is impossible to reach, because there is a run-time check guarding you from that:
However, the compiler must assume that reaching this return statement is possible, which would be an error in cases when
LOCAL_TYPEis not aFavoritePlace.You may want to reconsider the use of generics here: from the code snippet it appears that you need the generic argument to avoid type-casting the result to the desired type in the caller. However, the caller would then need to perform an additional check to see if the conversion inside your
RemoteToLocalhas succeeded. In this case, a methodmay be equally suited to the task, because it would be free of conversions that trick the compiler, and the structure of the calling code would remain the same.