OneOf icon indicating copy to clipboard operation
OneOf copied to clipboard

Unexpected behavior with interfaces

Open NWoodsman opened this issue 2 years ago • 2 comments

I'm having the below error, any thoughts on this? Hopefully the answer is not "don't use interface types".

OneOf<IFoo> test_fail = IFoo.AFoo; // CS0029: Cannot implicitly convert type <IFoo> to OneOf<IFoo>
OneOf<IFoo> test_pass = new Foo();

internal interface IFoo
{
    internal static IFoo AFoo => new Foo();
}

internal class Foo : IFoo {}

NWoodsman avatar Jul 08 '23 20:07 NWoodsman

for interfaces you have to use FromTX methods

OneOf<IFoo> test_fail = OneOf<IFoo>.FromT0(IFoo.AFoo);

for concrete types you can implement custom implicit/explicit operators (like it is descripted in the readme readme) or use source generator do to it for you, but in C# it is not possible to use implicit/explicit operators for interfaces so code like this

public partial class OneOfIFoo  : OneOfBase<IFoo>
{
	public OneOfIFoo(OneOf.OneOf<IFoo> _) : base(_) { }

	public static implicit operator OneOfIFoo(IFoo _) => new OneOfIFoo(_); //CS0552 'OneOfIFoo.implicit operator OneOfIFoo(UserQuery.IFoo)': user-defined conversions to or from an interface are not allowed
	public static explicit operator IFoo(OneOfIFoo _) => _.AsT0; //CS1503 Argument 1: cannot convert from 'IFoo' to 'OneOf.OneOf<IFoo>'

}

won't compile :/ (more on this on stack overflow)

romfir avatar Jul 11 '23 20:07 romfir

I actually hate interfaces so I'm quite glad it's disallowed. 🙃

On Tue, 11 Jul 2023, 21:31 romfir, @.***> wrote:

for interfaces you have to use FromTX methods

OneOf<IFoo> test_fail = OneOf<IFoo>.FromT0(IFoo.AFoo);

for concrete types you can implement custom implicit/explicit operators (like it is descripted in the readme readme https://github.com/mcintyre321/OneOf#reusable-oneof-types-using-oneofbase ) or use source generator do to it for you, but in C# it is not possible to use implicit/explicit operators for interfaces so code like this

public partial class OneOfIFoo : OneOfBase<IFoo>{ public OneOfIFoo(OneOf.OneOf<IFoo> ) : base() { }

public static implicit operator OneOfIFoo(IFoo ) => new OneOfIFoo(); //CS0552 'OneOfIFoo.implicit operator OneOfIFoo(UserQuery.IFoo)': user-defined conversions to or from an interface are not allowed public static explicit operator IFoo(OneOfIFoo _) => _.AsT0; //CS1503 Argument 1: cannot convert from 'IFoo' to 'OneOf.OneOf<IFoo>' }

won't compile :/ (more on this on stack overflow https://stackoverflow.com/questions/143485/implicit-operator-using-interfaces )

— Reply to this email directly, view it on GitHub https://github.com/mcintyre321/OneOf/issues/154#issuecomment-1631470043, or unsubscribe https://github.com/notifications/unsubscribe-auth/AACDJ6UNIGWVG6LJJZDF7YLXPWZ2XANCNFSM6AAAAAA2DBT7VU . You are receiving this because you are subscribed to this thread.Message ID: @.***>

mcintyre321 avatar Jul 11 '23 23:07 mcintyre321