I have a generic method in a base class similar to the following:
protected bool TryConvertTo<TIn, TOut>(TIn objIn, out TOut objOut)
where TIn : MyObjectBase
where TOut : MyObjectBase
{
objOut = objIn is TOut ? (TOut) (object) objIn : default (TOut);
return !ReferenceEquals(objOut, default (TOut));
}
Assume that I’m null-checking wherever necessary and handling any application exceptions accordingly. Is it bad practice to “double cast” objIn to object and then to TOut? If it is bad practice, are there any technical reasons why, or is it merely a reflection of an overall design issue?
I feel the usage is appropriate given my use case, but since I don’t normally use such an expression, I thought it might be safe to get the community’s opinion.
Given that you’ve constrained both of them to derive from a particular class (assuming
MyObjectBaseis indeed a class) why not just use:(I’m assuming there are no custom conversion operators or
==/!=overloads inMyObjectBase.)On the other hand, this feels like a fairly strange thing to want to do in the first place… are you sure it’s an appropriate design, leaving aside the implementation?