Introduction
I am aware that \"user-defined conversions to or from a base class are not allowed\". MSDN gives, as an explanation to this rule, \"You
(Invoking necromancy protocols...)
Here's my use-case:
class ParseResult
{
public static ParseResult Error(string message);
public static ParseResult Parsed(T value);
public bool IsError { get; }
public string ErrorMessage { get; }
public IEnumerable WarningMessages { get; }
public void AddWarning(string message);
}
class ParseResult : ParseResult
{
public static implicit operator ParseResult(ParseResult result); // Fails
public T Value { get; }
}
...
ParseResult ParseSomeBigLongTypeName()
{
if (SomethingIsBad)
return ParseResult.Error("something is bad");
return ParseResult.Parsed(new SomeBigLongTypeName());
}
Here Parsed()
can infer T
from it's parameter, but Error
can't, but it can return a typeless ParseResult
that is convertible to ParseResult
- or it would be if not for this error. The fix is to return and convert from a subtype:
class ParseResult
{
public static ErrorParseResult Error(string message);
...
}
class ErrorParseResult : ParseResult {}
class ParseResult
{
public static implicit operator ParseResult(ErrorParseResult result);
...
}
And everything is happy!