I am trying to create a method in an interface with a generic return type but I fail to cast the generic to a specific type/class. But if I put the generic on the interface
If you need your interface to support an arbitrary set of classes, and what classes are used is determined by the caller then something like this is the most general solution.
public class Bar : IFoo {
T foo() {
if (typeof(T)==typeof(Rain))
return new Rain() as T;
if (typeof(T)==typeof(Snow))
return new Snow() as T;
Throw new ArgumentException("Not implemented for " + typeof(T).Name);
}
}
If all your T's have a common interface and that is what you are interested in you could do;
public class Snow : IWeather {...}
public class Rain: IWeather {...}
public class Bar : IFoo {
IWeather foo() T : IWeather {
if (typeof(T)==typeof(Rain))
return new Rain();
if (typeof(T)==typeof(Snow))
return new Snow();
Throw new ArgumentException("Not implemented for " + typeof(T).Name);
}
}