C
C#5mo ago
Jason_Bjorn

✅ Two methods: struct and non-struct

Why does b.F(42) call the 2nd overload? 42 is a value-type which is what structs are?
public class Base
{
public virtual void F<T>(T? t) where T : struct { }
public virtual void F<T>(T? t) { }
}

Base b = new();
int? nullInt = null;
int? nonNullNullableInt = 42;

// These call the 1st overload.
b.F(nullInt);
b.F(nonNullNullableInt);
b.F(default(int?));

// These call the 2nd overload.
b.F(42);
b.F("Hello");
b.F(default(int));
public class Base
{
public virtual void F<T>(T? t) where T : struct { }
public virtual void F<T>(T? t) { }
}

Base b = new();
int? nullInt = null;
int? nonNullNullableInt = 42;

// These call the 1st overload.
b.F(nullInt);
b.F(nonNullNullableInt);
b.F(default(int?));

// These call the 2nd overload.
b.F(42);
b.F("Hello");
b.F(default(int));
6 Replies
reflectronic
reflectronic5mo ago
because calling the first overload would require converting into a Nullable<T> (a.k.a. T? when T is a struct) while the second overload does not require any conversion, so it is a closer match
Jason_Bjorn
Jason_BjornOP5mo ago
Thank you. If it did use the first one, would that involve boxing it?
reflectronic
reflectronic5mo ago
no, it is not a boxing conversion it is just a wrapper struct struct Nullable<T> { T value; bool hasValue; } which is blessed by the language
Jason_Bjorn
Jason_BjornOP5mo ago
thank you @reflectronic
Unknown User
Unknown User5mo ago
Message Not Public
Sign In & Join Server To View
MODiX
MODiX5mo ago
If you have no further questions, please use /close to mark the forum thread as answered
Want results from more Discord servers?
Add your server