Consider the following scenario.
I have a method that returns ISomething, but maybe Somethingor Wrapped<Something>. So I used the result for Somethingto use it, but it fails, any help as to why and how to resolve it would be greatly appreciated.
class Program
{
static void Main(string[] args)
{
var a = new DerivedSomething();
var b = (DerivedSomething)new Wrapped<DerivedSomething>(a);
var c = (DerivedSomething)_GetSomething(false);
var d = (DerivedSomething)_GetSomething(true);
var e = (DerivedSomething)(ISomething)new Wrapped<DerivedSomething>(a);
var works = ((DerivedSomething)_GetSomething(false)).DoSomethingElse();
var fails = ((DerivedSomething)_GetSomething(true)).DoSomethingElse();
}
private static ISomething _GetSomething(bool wrap)
{
var something = new DerivedSomething();
return wrap ? new Wrapped<DerivedSomething>(something) : (ISomething)something;
}
}
public interface ISomething
{
void DoSomething();
}
public abstract class Something : ISomething
{
public void DoSomething()
{
}
}
public class DerivedSomething : Something
{
public void DoSomething()
{
}
public void DoSomethingElse()
{
}
}
public class Wrapped<T> : ISomething
where T : ISomething
{
private readonly T _something;
public Wrapped(T something)
{
_something = something;
}
public void DoSomething()
{
_something.DoSomething();
}
public static explicit operator T(Wrapped<T> wrapped)
{
return wrapped._something;
}
}
It seems that if the type is displayed as an interface when trying to quit, then the operator was not found?
A โsimpleโ solution would be to write a โU-turnโ function, which, if desired, can expand Wrapped<Something>to Something, but I would prefer to use operators if possible.
Edit
I think the essence of the problem: outside _GetSomething()I donโt know whether Somethingor will be returned Wrapped<Something>.