trent_m

public virtual T MyMethod<T>()
{
if (typeof (T) != typeof (Collection<string>))
{
return default(T);
}
Collection<string> collection = new Collection<string>();

return (T)collection;
}

This method has the compile error on the red line above:

Cannot convert type 'System.Collections.ObjectModel.Collection<System.String>' to 'T'

Any reasoning would be appreciated.



Re: Visual C# Language Generic casting problem

BinaryCoder

It is not clear what the purpose of this function is. Could you explain what this method is supposed to do





Re: Visual C# Language Generic casting problem

:)Eric Han

thm99 wrote:

public virtual T MyMethod<T>()
{
if (typeof (T) != typeof (Collection<string>))
{
return default(T);
}
Collection<string> collection = new Collection<string>();

return (T)collection;
}

This method has the compile error on the red line above:

Cannot convert type 'System.Collections.ObjectModel.Collection<System.String>' to 'T'

Any reasoning would be appreciated.



Does the default is a new keyword in C#3.0





Re: Visual C# Language Generic casting problem

Mattias Sjogren

What's the point of having a generic method if it only allows one type (Collecton<string>) to be used

Anyway, I think you can get it to compile if you write

return (T)(object)collection;






Re: Visual C# Language Generic casting problem

thm99

Spot on Mattias but can you explain why I have to cast to object, it doesn't seem necessary

As for the code I posted the method actually uses another type than string and has some more logic but I just wanted to post a simple and concise example of the root problem.





Re: Visual C# Language Generic casting problem

Mattias Sjogren

Without the cast to object, the compiler has enough type information to know that the cast can't generally work. But when the type is object (or some other base class common to both the operand and T) it will at least try to make the cast.






Re: Visual C# Language Generic casting problem

nikov

> but can you explain why I have to cast to object, it doesn't seem necessary

You have to cast to object to make obvious that no conversions except implicit/explicit reference conversions are applicable here (particularly, user-defined conversion are not applicable).