C# implicit conversion from null

2 days ago 12
ARTICLE AD BOX

I have a struct that I allow implicit conversion from string or StringBuilder.

public ref struct StringParam { private string s; private StringBuilder sb; public static implicit operator StringParam(string s) { return new StringParam { s = s }; } public static implicit operator StringParam(StringBuilder sb) { return new StringParam { sb = sb }; } public override ToString() { return s ?? sb?.ToString(); } }

Is there any way to allow implicit casting from null without first explicitly casting the null to string or StringBuilder?

When I try to pass null without casting it to string, I get error CS0037: Cannot convert null to 'StringParam' because it is a non-nullable value type. If I remove one of the implicit conversions, that error goes away.

I tried the OverloadResolutionPriority attribute on the implicit operators, but I get error CS9262: Cannot use 'OverloadResolutionPriorityAttribute' on this member.

I tried making an implicit operator StringParam(object o) that would take precedence over string and StringBuilder, but I get error CS0553: user-defined conversions to or from a base type are not allowed.

I tried putting "#nullable enable" on the class, and made only one of the implicit conversions nullable, but it didn't have any affect on null resolution.

I don't know what else to try.

Read Entire Article