C
C#12mo ago
akaJB

❔ Attempting to create a Result<T, E> type, running into issues with subclasses

I want to create a Result<T, E> and I'm running into trouble with the following: let's say I have a class Foo and a subclass Bar : Foo. If I create an instance of Result<Bar, _> I had expected it to be assignable to Result<Foo, _> but that doesn't seem to be the case. For a fuller example see: https://dotnetfiddle.net/UEgC3P Is there a way that allows such an assignment? Else how can I ergonomically work with the compiler? I could of course create a new Result instance (like the below), but it's very verbose.
return result.IsSuccess
? Result<Foo, int>.AsOk(result.Value)
: Result<Foo, int>.AsError(result.Error);
return result.IsSuccess
? Result<Foo, int>.AsOk(result.Value)
: Result<Foo, int>.AsError(result.Error);
C# PlayGround | C# Online Compiler | .NET Fiddle
C# PlayGround | Test your C# code online with .NET Fiddle code editor.
7 Replies
Tarcisio
Tarcisio12mo ago
Contravariance and covariance are supported only on interfaces and delegates, not on concrete classes. Your Result<T, E> class is a concrete class, so contravariance and covariance don't apply. Read this to learn how you'd implement it
Tarcisio
Tarcisio12mo ago
Also you might also want to learn about implicit operators if you're making your own result type
Tarcisio
Tarcisio12mo ago
User-defined explicit and implicit conversion operators - provide c...
Learn how to define custom implicit and explicit type conversions in C#. The operators provide the functionality for casting an object to a new type.
akaJB
akaJB12mo ago
In my defense it's late, but I'm having a hard time understanding how to implement a result type via contravariant/covariance. Would you have a real world example of these concepts in practice? Fwiw I plan on looking at it in the morning with fresh eyes
ffmpeg -i me -f null -
your types should inherit from interfaces and then you use said interface types instead of concrete types
Accord
Accord12mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.