❔ 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.
C# PlayGround | C# Online Compiler | .NET Fiddle
C# PlayGround | Test your C# code online with .NET Fiddle code editor.
7 Replies
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 itCreating Variant Generic Interfaces (C#)
Learn how to create variant generic interfaces with covariant or contravariant generic type parameters.
Also you might also want to learn about implicit operators if you're making your own result type
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.
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
your types should inherit from interfaces and then you use said interface types instead of concrete types
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.