I was wondering if someone could think of a nice workaround for not being able to add an implicit cast operator, for object, on your own class. The following example illustrates the kind of code I would like
public class Response
{
public string Contents { get; set; }
public static implicit operator Response(object source)
{
return new Response { Contents = source.ToString(); };
}
}
This won't compile because it upsets the C# compiler and it tells me
user-defined conversions to or from a base class are not allowed
Turning response into Response and doing
public static implicit operator Response<T>(T source)
is unfortunately not an option. My guess is going to be no, but could anyone think of a nice workaround/hack to get this to work. I would love to be able to do
public Response Foo()
{
return new Bar();
}
and end up with a Response.Contents that said Whatever.Namespace.Bar