I have below methonds :-
protected T compare<T>(T val1, T val2)
{
return val1;
}
protected bool compare(int val1, int val2)
{
return true;
}
Now when I call Compare(10,20), we get true as output. Why does it call non T type method?
One more question I have is when we initialize a variable :- Object 0=10; Here boxing occurs but why does boxing occur here since Value types are inherited from reference types?
Why does it call non T type method?
Overload resolution takes the best match. Converting 10 and 20 to int
is clearly better (since there's no conversion at all) then going with a generic type.
why does boxing occur here since Value types are inherited from reference types
A variable of a value types on it's own is stored as a value on the stack. If you want to store it as a variable of a reference type than it's stored on a managed heap and some memory overhead is required there. For one thing, you need a pointer to where the value is stored and there are other "memory things" (I won't go to details, it's quite complicated down there).