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

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

Why don't you get burned by the wood benches in a sauna?

How can I differentiate duration vs starting time

What did I blunder at move 23?

What is formjacking?

Dot product with a constant

What is an explicit bijection in combinatorics?

typeof generic and casted type

Exploding Numbers

Can a planet be tidally unlocked?

What if you do not believe in the project benefits?

Why can all solutions to the simple harmonic motion equation be written in terms of sines and cosines?

How many copper coins fit inside a cubic foot?

Why and/or operations in python statement are behaving unexpectedly?

Are all power cords made equal?

Do these large-scale, human power-plant-tending robots from the Matrix movies have a name, in-universe or out?

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

SQL Server 2017 crashes when backing up because filepath is wrong

Isn't a semicolon (';') needed after a function declaration in C++?

How can I give a Ranger advantage on a check due to Favored Enemy without spoiling the story for the player?

Spells that would be effective against a Modern Day army but would NOT destroy a fantasy one

Coworker is trying to get me to sign his petition to run for office. How to decline politely?

Is there any danger of my neighbor having my wife's signature?

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



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













7















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
    1 hour 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
    1 hour ago
















7















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
    1 hour 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
    1 hour ago














7












7








7








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 53 mins ago









Uwe Keim

27.5k32131212




27.5k32131212










asked 1 hour ago









user3450929user3450929

654




654








  • 3





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

    – João Paulo Amorim
    1 hour 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
    1 hour 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
    1 hour 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
    1 hour 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
1 hour ago





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

– João Paulo Amorim
1 hour 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
1 hour 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
1 hour ago












4 Answers
4






active

oldest

votes


















16














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

































    2














    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









          16














          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






























            16














            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




























              16












              16








              16







              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 29 mins ago

























              answered 1 hour ago









              HeinziHeinzi

              123k38269408




              123k38269408

























                  2














                  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




























                    2














                    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


























                      2












                      2








                      2







                      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 1 hour 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 50 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 1 hour 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

                                          Szabolcs (Ungheria) Altri progetti | Menu di navigazione48°10′14.56″N 21°29′33.14″E /...

                                          Discografia di Klaus Schulze Indice Album in studio | Album dal vivo | Singoli | Antologie | Colonne...

                                          How to make inet_server_addr() return localhost in spite of ::1/128RETURN NEXT in Postgres FunctionConnect to...