سؤال

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).

نصائح أخرى

Because compare(int, int) is considered a better match than compare(T, T), when overload resolution kicks in.

From section 7.5.3 of the C# specification:

If MP is a non-generic method and MQ is a generic method, then MP is better than MQ.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top