DCSIMG
typeof and GetType are not the same for nullable types - It's All About Causality

It's All About Causality

של יוסי תאגורי
I Drink Wine Therefore I Have To Pee

המלצות


שווה קריאה

typeof and GetType are not the same for nullable types

After years of not writing code that runs in production I'm just delighted to find out nifty things about the framework. Here is a piece of code:

   1: public static string Format<T>(T value)
   2: {
   3:     Type t1 = typeof(T);
   4:     Type t2 = value.GetType();
   5: }
t1 != t2 when it comes to nullable tyeps. if you fall Format with a nullable tyep of int? t1 will be int? and t2 would be a simple int. anyone knows why?

תוכן התגובה

Slava כתב/ה:

In your example T is Generic Type, thefore when using typeof(T) it returns the result of function GetGenericTypeDefinition().

# October 22, 2007 5:35 PM

עומר ון קלוטן כתב/ה:

ורק אני מתפלא על זה שיש קוד בבלוג של יוסי? D:

# October 23, 2007 12:34 AM

Vladimir Kofman כתב/ה:

It's because of the boxing.

Before calling the .GetType() method the parameter "value" is boxed, so actual call is executed on System.Int32

This would happen for any method of value type that is not explicitly overriden in that type.

Here's the IL:

IL_0001:  ldarga.s   'value'

 IL_0003:  constrained. !!T

 IL_0009:  callvirt   instance class [mscorlib]System.Type [mscorlib]System.Object::GetType()

And here's the explanation of "constrained": msdn2.microsoft.com/.../system.reflection.emit.opcodes.constrained.aspx

# October 23, 2007 2:16 PM

Yosi Taguri כתב/ה:

תודה על ההסברים, כל יום לומדים משהו חדש.

# October 25, 2007 11:01 AM

מנשה כתב/ה:

מזל שאף אחד לא שאל אותך את השאלה הזאת בראיון עבודה.

והיה קובע בשניה שאתה לא יודע כלום על פי השאלה הזאת.

לך תסביר לו שאתה טיפוס שלומד כל יום דבר חדש.

# November 22, 2007 7:53 AM

Yosi Taguri כתב/ה:

מנשה, הייתי אומר שאני לא יודע!

חוץ מזה, שאלות קומפיילרים בראיונות הם שאלות נבזיות, אני לא נוהג לשאול אותם כי אני לא מצפה מאנשים שיהיו קומפיילרים אנושיים.

# November 22, 2007 8:25 AM