typeof generic and casted typeWhen and where to use GetType() or typeof()?When is the generic type resolved...

Multiple null checks in Java 8

What does @ mean in a hostname in DNS configuration?

How bad is a Computer Science course that doesn't teach Design Patterns?

A cancellation property for permutations?

Why does this quiz question say that protons and electrons do not combine to form neutrons?

Boss asked me to sign a resignation paper without a date on it along with my new contract

Have the UK Conservatives lost the working majority and if so, what does this mean?

Why is it that Bernie Sanders always called a "socialist"?

Is there a way to pause a running process on Linux systems and resume later?

Why would you use 2 alternate layout buttons instead of 1, when only one can be selected at once

What legally stops the UK from having another referendum on Brexit

Is Screenshot Time-tracking Common?

Is it common to refer to someone as "Prof. Dr. [LastName]"?

How can I make my enemies feel real and make combat more engaging?

When distributing a Linux kernel driver as source code, what's the difference between Proprietary and GPL license?

Reduce Reflections

Cryptic cross... with words

Do the speed limit reductions due to pollution also apply to electric cars in France?

Sets which are both Sum-free and Product-free.

How Create a list of the first 10,000 digits of Pi and sum it?

Can someone explain the need for perturbation theory in QM?

Why is Shelob considered evil?

How do I add a strong "onion flavor" to the biryani (in restaurant style)?

3D buried view in Tikz



typeof generic and casted type


When and where to use GetType() or typeof()?When is the generic type resolved in c#?Run-time type vs compile-time type in C#Cast int to enum in C#Create Generic method constraining T to an EnumHow do I use reflection to call a generic method?Collections.emptyList() returns a List<Object>?How do I make the method return type generic?Type Checking: typeof, GetType, or is?Using Mockito to mock classes with generic parametersHow do I generate a random int number in C#?Google Gson - deserialize list<class> object? (generic type)Unable to cast object of type System.Int32 to System.Object[] when calling generic method with parameters via reflection













6















Let's say we have generic method:



public void GenericMethod<T>(T item)
{
var typeOf = typeof(T);
var getType = item.GetType();
}


And we are invoking it with the following parameters:



GenericMethod(1)
GenericMethod((object) 1)


The results are:



typeOf = System.Int32
getType = System.Int32


and



typeOf = System.Object
getType = System.Int32


Can someone explain me why typeof integer casted to object returns System.Object, but .GetType() returns System.Int32?










share|improve this question




















  • 3





    typeof takes a type name (which you specify at compile time), GetType gets the runtime type of an instance.

    – João Paulo Amorim
    57 mins ago






  • 1





    Also, if you find yourself doing any kind of type test inside a generic, ask yourself whether you've picked the right tool for the job. Because it may mean that you fail to work properly at runtime something that you "promised" at compile time you could do (by saying you could work for any type, subject to any generic type constraints on that type parameter)

    – Damien_The_Unbeliever
    55 mins ago
















6















Let's say we have generic method:



public void GenericMethod<T>(T item)
{
var typeOf = typeof(T);
var getType = item.GetType();
}


And we are invoking it with the following parameters:



GenericMethod(1)
GenericMethod((object) 1)


The results are:



typeOf = System.Int32
getType = System.Int32


and



typeOf = System.Object
getType = System.Int32


Can someone explain me why typeof integer casted to object returns System.Object, but .GetType() returns System.Int32?










share|improve this question




















  • 3





    typeof takes a type name (which you specify at compile time), GetType gets the runtime type of an instance.

    – João Paulo Amorim
    57 mins ago






  • 1





    Also, if you find yourself doing any kind of type test inside a generic, ask yourself whether you've picked the right tool for the job. Because it may mean that you fail to work properly at runtime something that you "promised" at compile time you could do (by saying you could work for any type, subject to any generic type constraints on that type parameter)

    – Damien_The_Unbeliever
    55 mins ago














6












6








6








Let's say we have generic method:



public void GenericMethod<T>(T item)
{
var typeOf = typeof(T);
var getType = item.GetType();
}


And we are invoking it with the following parameters:



GenericMethod(1)
GenericMethod((object) 1)


The results are:



typeOf = System.Int32
getType = System.Int32


and



typeOf = System.Object
getType = System.Int32


Can someone explain me why typeof integer casted to object returns System.Object, but .GetType() returns System.Int32?










share|improve this question
















Let's say we have generic method:



public void GenericMethod<T>(T item)
{
var typeOf = typeof(T);
var getType = item.GetType();
}


And we are invoking it with the following parameters:



GenericMethod(1)
GenericMethod((object) 1)


The results are:



typeOf = System.Int32
getType = System.Int32


and



typeOf = System.Object
getType = System.Int32


Can someone explain me why typeof integer casted to object returns System.Object, but .GetType() returns System.Int32?







c# generics






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 45 mins ago









Uwe Keim

27.5k32131212




27.5k32131212










asked 59 mins ago









user3450929user3450929

604




604








  • 3





    typeof takes a type name (which you specify at compile time), GetType gets the runtime type of an instance.

    – João Paulo Amorim
    57 mins ago






  • 1





    Also, if you find yourself doing any kind of type test inside a generic, ask yourself whether you've picked the right tool for the job. Because it may mean that you fail to work properly at runtime something that you "promised" at compile time you could do (by saying you could work for any type, subject to any generic type constraints on that type parameter)

    – Damien_The_Unbeliever
    55 mins ago














  • 3





    typeof takes a type name (which you specify at compile time), GetType gets the runtime type of an instance.

    – João Paulo Amorim
    57 mins ago






  • 1





    Also, if you find yourself doing any kind of type test inside a generic, ask yourself whether you've picked the right tool for the job. Because it may mean that you fail to work properly at runtime something that you "promised" at compile time you could do (by saying you could work for any type, subject to any generic type constraints on that type parameter)

    – Damien_The_Unbeliever
    55 mins ago








3




3





typeof takes a type name (which you specify at compile time), GetType gets the runtime type of an instance.

– João Paulo Amorim
57 mins ago





typeof takes a type name (which you specify at compile time), GetType gets the runtime type of an instance.

– João Paulo Amorim
57 mins ago




1




1





Also, if you find yourself doing any kind of type test inside a generic, ask yourself whether you've picked the right tool for the job. Because it may mean that you fail to work properly at runtime something that you "promised" at compile time you could do (by saying you could work for any type, subject to any generic type constraints on that type parameter)

– Damien_The_Unbeliever
55 mins ago





Also, if you find yourself doing any kind of type test inside a generic, ask yourself whether you've picked the right tool for the job. Because it may mean that you fail to work properly at runtime something that you "promised" at compile time you could do (by saying you could work for any type, subject to any generic type constraints on that type parameter)

– Damien_The_Unbeliever
55 mins ago












4 Answers
4






active

oldest

votes


















12














typeof returns the static (compile-time) type of the generic parameter T.



GetType returns the dynamic (run-time) type of the value contained in variable item.





The difference is easier to see if you make your method non-generic. Let's assume that B is a subtype of A:



public void NonGenericMethod(A item)
{
var typeOf = typeof(A);
var getType = item.GetType();
}


In that case, calling NonGenericMethod(new B()) would yield



A
B


Recommended further reading:




  • Run-time type vs compile-time type in C#




Now, you might ask: Why did you use NonGenericMethod(A item) in your example instead of NonGenericMethod(B item)? That's a very good question! Consider the following (non-generic) example code:



public static void NonGenericMethod(A item)
{
Console.WriteLine("Method A");
var typeOf = typeof(A);
var getType = item.GetType();
}
public static void NonGenericMethod(B item)
{
Console.WriteLine("Method B");
var typeOf = typeof(B);
var getType = item.GetType();
}


What do you get when you call NonGenericMethod((A) new B()) (which is analogous to the argument (object) 1 in your example)?



Method A
A
B


Why? Because overload resolution is done at compile-time, not at run-time. At compile-time, the type of the expression (A) new B() is A, just like the compile-time type of (object) 1 is object.



Recommended further reading:




  • When is the generic type resolved in c#?






share|improve this answer

































    1














    In GenericMethod((object) 1), T will be object. typeof reflects that.



    But item.GetType(); is a virtual method and will execute at runtime on Int32.






    share|improve this answer































      1














      The call to GetType gets resolved at runtime, while typeof is resolved at compile time.
      That is why it is giving different results.
      you can check here - When and where to use GetType() or typeof()?






      share|improve this answer































        0














        This Tells me Typeof gives you compile time type whereas GetType gives you Exact Run time type.






        share|improve this answer























          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54827467%2ftypeof-generic-and-casted-type%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          4 Answers
          4






          active

          oldest

          votes








          4 Answers
          4






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          12














          typeof returns the static (compile-time) type of the generic parameter T.



          GetType returns the dynamic (run-time) type of the value contained in variable item.





          The difference is easier to see if you make your method non-generic. Let's assume that B is a subtype of A:



          public void NonGenericMethod(A item)
          {
          var typeOf = typeof(A);
          var getType = item.GetType();
          }


          In that case, calling NonGenericMethod(new B()) would yield



          A
          B


          Recommended further reading:




          • Run-time type vs compile-time type in C#




          Now, you might ask: Why did you use NonGenericMethod(A item) in your example instead of NonGenericMethod(B item)? That's a very good question! Consider the following (non-generic) example code:



          public static void NonGenericMethod(A item)
          {
          Console.WriteLine("Method A");
          var typeOf = typeof(A);
          var getType = item.GetType();
          }
          public static void NonGenericMethod(B item)
          {
          Console.WriteLine("Method B");
          var typeOf = typeof(B);
          var getType = item.GetType();
          }


          What do you get when you call NonGenericMethod((A) new B()) (which is analogous to the argument (object) 1 in your example)?



          Method A
          A
          B


          Why? Because overload resolution is done at compile-time, not at run-time. At compile-time, the type of the expression (A) new B() is A, just like the compile-time type of (object) 1 is object.



          Recommended further reading:




          • When is the generic type resolved in c#?






          share|improve this answer






























            12














            typeof returns the static (compile-time) type of the generic parameter T.



            GetType returns the dynamic (run-time) type of the value contained in variable item.





            The difference is easier to see if you make your method non-generic. Let's assume that B is a subtype of A:



            public void NonGenericMethod(A item)
            {
            var typeOf = typeof(A);
            var getType = item.GetType();
            }


            In that case, calling NonGenericMethod(new B()) would yield



            A
            B


            Recommended further reading:




            • Run-time type vs compile-time type in C#




            Now, you might ask: Why did you use NonGenericMethod(A item) in your example instead of NonGenericMethod(B item)? That's a very good question! Consider the following (non-generic) example code:



            public static void NonGenericMethod(A item)
            {
            Console.WriteLine("Method A");
            var typeOf = typeof(A);
            var getType = item.GetType();
            }
            public static void NonGenericMethod(B item)
            {
            Console.WriteLine("Method B");
            var typeOf = typeof(B);
            var getType = item.GetType();
            }


            What do you get when you call NonGenericMethod((A) new B()) (which is analogous to the argument (object) 1 in your example)?



            Method A
            A
            B


            Why? Because overload resolution is done at compile-time, not at run-time. At compile-time, the type of the expression (A) new B() is A, just like the compile-time type of (object) 1 is object.



            Recommended further reading:




            • When is the generic type resolved in c#?






            share|improve this answer




























              12












              12








              12







              typeof returns the static (compile-time) type of the generic parameter T.



              GetType returns the dynamic (run-time) type of the value contained in variable item.





              The difference is easier to see if you make your method non-generic. Let's assume that B is a subtype of A:



              public void NonGenericMethod(A item)
              {
              var typeOf = typeof(A);
              var getType = item.GetType();
              }


              In that case, calling NonGenericMethod(new B()) would yield



              A
              B


              Recommended further reading:




              • Run-time type vs compile-time type in C#




              Now, you might ask: Why did you use NonGenericMethod(A item) in your example instead of NonGenericMethod(B item)? That's a very good question! Consider the following (non-generic) example code:



              public static void NonGenericMethod(A item)
              {
              Console.WriteLine("Method A");
              var typeOf = typeof(A);
              var getType = item.GetType();
              }
              public static void NonGenericMethod(B item)
              {
              Console.WriteLine("Method B");
              var typeOf = typeof(B);
              var getType = item.GetType();
              }


              What do you get when you call NonGenericMethod((A) new B()) (which is analogous to the argument (object) 1 in your example)?



              Method A
              A
              B


              Why? Because overload resolution is done at compile-time, not at run-time. At compile-time, the type of the expression (A) new B() is A, just like the compile-time type of (object) 1 is object.



              Recommended further reading:




              • When is the generic type resolved in c#?






              share|improve this answer















              typeof returns the static (compile-time) type of the generic parameter T.



              GetType returns the dynamic (run-time) type of the value contained in variable item.





              The difference is easier to see if you make your method non-generic. Let's assume that B is a subtype of A:



              public void NonGenericMethod(A item)
              {
              var typeOf = typeof(A);
              var getType = item.GetType();
              }


              In that case, calling NonGenericMethod(new B()) would yield



              A
              B


              Recommended further reading:




              • Run-time type vs compile-time type in C#




              Now, you might ask: Why did you use NonGenericMethod(A item) in your example instead of NonGenericMethod(B item)? That's a very good question! Consider the following (non-generic) example code:



              public static void NonGenericMethod(A item)
              {
              Console.WriteLine("Method A");
              var typeOf = typeof(A);
              var getType = item.GetType();
              }
              public static void NonGenericMethod(B item)
              {
              Console.WriteLine("Method B");
              var typeOf = typeof(B);
              var getType = item.GetType();
              }


              What do you get when you call NonGenericMethod((A) new B()) (which is analogous to the argument (object) 1 in your example)?



              Method A
              A
              B


              Why? Because overload resolution is done at compile-time, not at run-time. At compile-time, the type of the expression (A) new B() is A, just like the compile-time type of (object) 1 is object.



              Recommended further reading:




              • When is the generic type resolved in c#?







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited 21 mins ago

























              answered 56 mins ago









              HeinziHeinzi

              123k38269408




              123k38269408

























                  1














                  In GenericMethod((object) 1), T will be object. typeof reflects that.



                  But item.GetType(); is a virtual method and will execute at runtime on Int32.






                  share|improve this answer




























                    1














                    In GenericMethod((object) 1), T will be object. typeof reflects that.



                    But item.GetType(); is a virtual method and will execute at runtime on Int32.






                    share|improve this answer


























                      1












                      1








                      1







                      In GenericMethod((object) 1), T will be object. typeof reflects that.



                      But item.GetType(); is a virtual method and will execute at runtime on Int32.






                      share|improve this answer













                      In GenericMethod((object) 1), T will be object. typeof reflects that.



                      But item.GetType(); is a virtual method and will execute at runtime on Int32.







                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered 54 mins ago









                      Henk HoltermanHenk Holterman

                      210k22232404




                      210k22232404























                          1














                          The call to GetType gets resolved at runtime, while typeof is resolved at compile time.
                          That is why it is giving different results.
                          you can check here - When and where to use GetType() or typeof()?






                          share|improve this answer




























                            1














                            The call to GetType gets resolved at runtime, while typeof is resolved at compile time.
                            That is why it is giving different results.
                            you can check here - When and where to use GetType() or typeof()?






                            share|improve this answer


























                              1












                              1








                              1







                              The call to GetType gets resolved at runtime, while typeof is resolved at compile time.
                              That is why it is giving different results.
                              you can check here - When and where to use GetType() or typeof()?






                              share|improve this answer













                              The call to GetType gets resolved at runtime, while typeof is resolved at compile time.
                              That is why it is giving different results.
                              you can check here - When and where to use GetType() or typeof()?







                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered 42 mins ago









                              Deepankshee JainDeepankshee Jain

                              112




                              112























                                  0














                                  This Tells me Typeof gives you compile time type whereas GetType gives you Exact Run time type.






                                  share|improve this answer




























                                    0














                                    This Tells me Typeof gives you compile time type whereas GetType gives you Exact Run time type.






                                    share|improve this answer


























                                      0












                                      0








                                      0







                                      This Tells me Typeof gives you compile time type whereas GetType gives you Exact Run time type.






                                      share|improve this answer













                                      This Tells me Typeof gives you compile time type whereas GetType gives you Exact Run time type.







                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered 54 mins ago









                                      Gagan DeepGagan Deep

                                      76616




                                      76616






























                                          draft saved

                                          draft discarded




















































                                          Thanks for contributing an answer to Stack Overflow!


                                          • Please be sure to answer the question. Provide details and share your research!

                                          But avoid



                                          • Asking for help, clarification, or responding to other answers.

                                          • Making statements based on opinion; back them up with references or personal experience.


                                          To learn more, see our tips on writing great answers.




                                          draft saved


                                          draft discarded














                                          StackExchange.ready(
                                          function () {
                                          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54827467%2ftypeof-generic-and-casted-type%23new-answer', 'question_page');
                                          }
                                          );

                                          Post as a guest















                                          Required, but never shown





















































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown

































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown







                                          Popular posts from this blog

                                          Щит и меч (фильм) Содержание Названия серий | Сюжет |...

                                          Венесуэла на летних Олимпийских играх 2000 Содержание Состав...

                                          Meter-Bus Содержание Параметры шины | Стандартизация |...