Type int? vs type intNullable<int> vs. int? - Is there any difference?How is the boxing/unboxing behavior of Nullable<T> possible?Cast int to enum in C#Create Generic method constraining T to an EnumRandom number generator only generating one random numberUsing LINQ to remove elements from a List<T>Get int value from enum in C#Type Checking: typeof, GetType, or is?Distinct() with lambda?How do I generate a random int number?Call one constructor from anotherTry-catch speeding up my code?

Is this apparent Class Action settlement a spam message?

Purchasing a ticket for someone else in another country?

What is the best translation for "slot" in the context of multiplayer video games?

Why not increase contact surface when reentering the atmosphere?

Fastening aluminum fascia to wooden subfascia

Class Action - which options I have?

Risk of infection at the gym?

How to run a prison with the smallest amount of guards?

Failed to fetch jessie backports repository

Hostile work environment after whistle-blowing on coworker and our boss. What do I do?

How can a function with a hole (removable discontinuity) equal a function with no hole?

Integer addition + constant, is it a group?

How to safely derail a train during transit?

What is the intuitive meaning of having a linear relationship between the logs of two variables?

Why are there no referendums in the US?

How can I get through very long and very dry, but also very useful technical documents when learning a new tool?

Is exact Kanji stroke length important?

Is this version of a gravity generator feasible?

Trouble understanding the speech of overseas colleagues

How to check is there any negative term in a large list?

Detecting if an element is found inside a container

Applicability of Single Responsibility Principle

Customer Requests (Sometimes) Drive Me Bonkers!

For a non-Jew, is there a punishment for not observing the 7 Noahide Laws?



Type int? vs type int


Nullable<int> vs. int? - Is there any difference?How is the boxing/unboxing behavior of Nullable<T> possible?Cast int to enum in C#Create Generic method constraining T to an EnumRandom number generator only generating one random numberUsing LINQ to remove elements from a List<T>Get int value from enum in C#Type Checking: typeof, GetType, or is?Distinct() with lambda?How do I generate a random int number?Call one constructor from anotherTry-catch speeding up my code?













24















I've this comparison which equals false as expected



bool eq = typeof(int?).Equals(typeof(int));


now I have this code



List<object> items = new List<object>() (int?)123 ;
int result = items.OfType<int>().FirstOrDefault();


but this returns 123 - anyway that value is of type int?



How can this be?










share|improve this question






















  • int? boxed as int , and basically every Nullable type, Edit : Marc Gravell have the full answer

    – styx
    15 hours ago












  • Related post about nullable type: stackoverflow.com/questions/4028830/…. This is called as "type lifting".

    – Tetsuya Yamamoto
    15 hours ago











  • Before reading this topic I wouldn't even guess that even List<int?> already holds just int types. Proof

    – Sinatr
    15 hours ago






  • 7





    @Sinatr no, that is incorrect; List<int?> holds int?. The important distinction in this example is the use of List<object>. What you're seeing in that "proof" is something very different; GetType() on any T? either returns the T, or throws a NRE. It never returns T? - better example: dotnetfiddle.net/3Gy3Fa - and as for why: because GetType() is non-virtual, it cannot be overridden, and thus calling GetType() is a boxing operation (even if used via "constrained call"). And when you box a T?, you either get a T as an object, or a null.

    – Marc Gravell
    15 hours ago












  • @TetsuyaYamamoto That is not a relevant link. How is the boxing/unboxing behavior of Nullable<T> possible? is.

    – GSerg
    12 hours ago















24















I've this comparison which equals false as expected



bool eq = typeof(int?).Equals(typeof(int));


now I have this code



List<object> items = new List<object>() (int?)123 ;
int result = items.OfType<int>().FirstOrDefault();


but this returns 123 - anyway that value is of type int?



How can this be?










share|improve this question






















  • int? boxed as int , and basically every Nullable type, Edit : Marc Gravell have the full answer

    – styx
    15 hours ago












  • Related post about nullable type: stackoverflow.com/questions/4028830/…. This is called as "type lifting".

    – Tetsuya Yamamoto
    15 hours ago











  • Before reading this topic I wouldn't even guess that even List<int?> already holds just int types. Proof

    – Sinatr
    15 hours ago






  • 7





    @Sinatr no, that is incorrect; List<int?> holds int?. The important distinction in this example is the use of List<object>. What you're seeing in that "proof" is something very different; GetType() on any T? either returns the T, or throws a NRE. It never returns T? - better example: dotnetfiddle.net/3Gy3Fa - and as for why: because GetType() is non-virtual, it cannot be overridden, and thus calling GetType() is a boxing operation (even if used via "constrained call"). And when you box a T?, you either get a T as an object, or a null.

    – Marc Gravell
    15 hours ago












  • @TetsuyaYamamoto That is not a relevant link. How is the boxing/unboxing behavior of Nullable<T> possible? is.

    – GSerg
    12 hours ago













24












24








24


3






I've this comparison which equals false as expected



bool eq = typeof(int?).Equals(typeof(int));


now I have this code



List<object> items = new List<object>() (int?)123 ;
int result = items.OfType<int>().FirstOrDefault();


but this returns 123 - anyway that value is of type int?



How can this be?










share|improve this question














I've this comparison which equals false as expected



bool eq = typeof(int?).Equals(typeof(int));


now I have this code



List<object> items = new List<object>() (int?)123 ;
int result = items.OfType<int>().FirstOrDefault();


but this returns 123 - anyway that value is of type int?



How can this be?







c# casting






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked 15 hours ago









Dr. SnailDr. Snail

693628




693628












  • int? boxed as int , and basically every Nullable type, Edit : Marc Gravell have the full answer

    – styx
    15 hours ago












  • Related post about nullable type: stackoverflow.com/questions/4028830/…. This is called as "type lifting".

    – Tetsuya Yamamoto
    15 hours ago











  • Before reading this topic I wouldn't even guess that even List<int?> already holds just int types. Proof

    – Sinatr
    15 hours ago






  • 7





    @Sinatr no, that is incorrect; List<int?> holds int?. The important distinction in this example is the use of List<object>. What you're seeing in that "proof" is something very different; GetType() on any T? either returns the T, or throws a NRE. It never returns T? - better example: dotnetfiddle.net/3Gy3Fa - and as for why: because GetType() is non-virtual, it cannot be overridden, and thus calling GetType() is a boxing operation (even if used via "constrained call"). And when you box a T?, you either get a T as an object, or a null.

    – Marc Gravell
    15 hours ago












  • @TetsuyaYamamoto That is not a relevant link. How is the boxing/unboxing behavior of Nullable<T> possible? is.

    – GSerg
    12 hours ago

















  • int? boxed as int , and basically every Nullable type, Edit : Marc Gravell have the full answer

    – styx
    15 hours ago












  • Related post about nullable type: stackoverflow.com/questions/4028830/…. This is called as "type lifting".

    – Tetsuya Yamamoto
    15 hours ago











  • Before reading this topic I wouldn't even guess that even List<int?> already holds just int types. Proof

    – Sinatr
    15 hours ago






  • 7





    @Sinatr no, that is incorrect; List<int?> holds int?. The important distinction in this example is the use of List<object>. What you're seeing in that "proof" is something very different; GetType() on any T? either returns the T, or throws a NRE. It never returns T? - better example: dotnetfiddle.net/3Gy3Fa - and as for why: because GetType() is non-virtual, it cannot be overridden, and thus calling GetType() is a boxing operation (even if used via "constrained call"). And when you box a T?, you either get a T as an object, or a null.

    – Marc Gravell
    15 hours ago












  • @TetsuyaYamamoto That is not a relevant link. How is the boxing/unboxing behavior of Nullable<T> possible? is.

    – GSerg
    12 hours ago
















int? boxed as int , and basically every Nullable type, Edit : Marc Gravell have the full answer

– styx
15 hours ago






int? boxed as int , and basically every Nullable type, Edit : Marc Gravell have the full answer

– styx
15 hours ago














Related post about nullable type: stackoverflow.com/questions/4028830/…. This is called as "type lifting".

– Tetsuya Yamamoto
15 hours ago





Related post about nullable type: stackoverflow.com/questions/4028830/…. This is called as "type lifting".

– Tetsuya Yamamoto
15 hours ago













Before reading this topic I wouldn't even guess that even List<int?> already holds just int types. Proof

– Sinatr
15 hours ago





Before reading this topic I wouldn't even guess that even List<int?> already holds just int types. Proof

– Sinatr
15 hours ago




7




7





@Sinatr no, that is incorrect; List<int?> holds int?. The important distinction in this example is the use of List<object>. What you're seeing in that "proof" is something very different; GetType() on any T? either returns the T, or throws a NRE. It never returns T? - better example: dotnetfiddle.net/3Gy3Fa - and as for why: because GetType() is non-virtual, it cannot be overridden, and thus calling GetType() is a boxing operation (even if used via "constrained call"). And when you box a T?, you either get a T as an object, or a null.

– Marc Gravell
15 hours ago






@Sinatr no, that is incorrect; List<int?> holds int?. The important distinction in this example is the use of List<object>. What you're seeing in that "proof" is something very different; GetType() on any T? either returns the T, or throws a NRE. It never returns T? - better example: dotnetfiddle.net/3Gy3Fa - and as for why: because GetType() is non-virtual, it cannot be overridden, and thus calling GetType() is a boxing operation (even if used via "constrained call"). And when you box a T?, you either get a T as an object, or a null.

– Marc Gravell
15 hours ago














@TetsuyaYamamoto That is not a relevant link. How is the boxing/unboxing behavior of Nullable<T> possible? is.

– GSerg
12 hours ago





@TetsuyaYamamoto That is not a relevant link. How is the boxing/unboxing behavior of Nullable<T> possible? is.

– GSerg
12 hours ago












2 Answers
2






active

oldest

votes


















39














Nullable types have special "boxing" rules; "boxing" is when a value-type is treated as object, as per your code. Unlike regular value-types, a nullable value-type is boxed either as null (regular null, no type), or as the non-nullable type (the T in T?). So: an int? is boxed as an int, not an int?. Then when you use OfType<int>() on it, you get all the values that are int, which is: the single value you passed in, since it is of type int.






share|improve this answer























  • phew ok thank you for that explanaion. Is that C# basic knowledge?

    – Dr. Snail
    15 hours ago






  • 12





    @Dr.Snail "basic" is relative / subjective, and I'd wager that a good percentage of developers never have a need to know that nuance; it is useful context if you're dealing with boxing, though... and technically it isn't really C# knowledge, but rather: .NET knowledge (it would apply to all languages)

    – Marc Gravell
    15 hours ago












  • How would the query to obtain only int? from above items list will look like?

    – Sinatr
    15 hours ago







  • 4





    @Sinatr you can't - the list never contains int? - it only contains int because of the boxing rules on nullable types

    – Marc Gravell
    15 hours ago












  • Maybe I'm missing something but it returning 123 makes perfect sense to be. This long explanation does not. You added an int to a list and said give me all the integers in the list. The ? makes it so you can pass a null in the place of an int.

    – Kyle Johnson
    4 hours ago



















4














A nullable value type is boxed by the following rules:



  • If HasValue returns false, the null reference is produced.

  • If HasValue returns true, a value of the underlying value type T is
    boxed, not the instance of nullable.


In your example second rule has been followed as you have value, e.g.
var i = (object)(int?)123;






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%2f55372675%2ftype-int-vs-type-int%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    39














    Nullable types have special "boxing" rules; "boxing" is when a value-type is treated as object, as per your code. Unlike regular value-types, a nullable value-type is boxed either as null (regular null, no type), or as the non-nullable type (the T in T?). So: an int? is boxed as an int, not an int?. Then when you use OfType<int>() on it, you get all the values that are int, which is: the single value you passed in, since it is of type int.






    share|improve this answer























    • phew ok thank you for that explanaion. Is that C# basic knowledge?

      – Dr. Snail
      15 hours ago






    • 12





      @Dr.Snail "basic" is relative / subjective, and I'd wager that a good percentage of developers never have a need to know that nuance; it is useful context if you're dealing with boxing, though... and technically it isn't really C# knowledge, but rather: .NET knowledge (it would apply to all languages)

      – Marc Gravell
      15 hours ago












    • How would the query to obtain only int? from above items list will look like?

      – Sinatr
      15 hours ago







    • 4





      @Sinatr you can't - the list never contains int? - it only contains int because of the boxing rules on nullable types

      – Marc Gravell
      15 hours ago












    • Maybe I'm missing something but it returning 123 makes perfect sense to be. This long explanation does not. You added an int to a list and said give me all the integers in the list. The ? makes it so you can pass a null in the place of an int.

      – Kyle Johnson
      4 hours ago
















    39














    Nullable types have special "boxing" rules; "boxing" is when a value-type is treated as object, as per your code. Unlike regular value-types, a nullable value-type is boxed either as null (regular null, no type), or as the non-nullable type (the T in T?). So: an int? is boxed as an int, not an int?. Then when you use OfType<int>() on it, you get all the values that are int, which is: the single value you passed in, since it is of type int.






    share|improve this answer























    • phew ok thank you for that explanaion. Is that C# basic knowledge?

      – Dr. Snail
      15 hours ago






    • 12





      @Dr.Snail "basic" is relative / subjective, and I'd wager that a good percentage of developers never have a need to know that nuance; it is useful context if you're dealing with boxing, though... and technically it isn't really C# knowledge, but rather: .NET knowledge (it would apply to all languages)

      – Marc Gravell
      15 hours ago












    • How would the query to obtain only int? from above items list will look like?

      – Sinatr
      15 hours ago







    • 4





      @Sinatr you can't - the list never contains int? - it only contains int because of the boxing rules on nullable types

      – Marc Gravell
      15 hours ago












    • Maybe I'm missing something but it returning 123 makes perfect sense to be. This long explanation does not. You added an int to a list and said give me all the integers in the list. The ? makes it so you can pass a null in the place of an int.

      – Kyle Johnson
      4 hours ago














    39












    39








    39







    Nullable types have special "boxing" rules; "boxing" is when a value-type is treated as object, as per your code. Unlike regular value-types, a nullable value-type is boxed either as null (regular null, no type), or as the non-nullable type (the T in T?). So: an int? is boxed as an int, not an int?. Then when you use OfType<int>() on it, you get all the values that are int, which is: the single value you passed in, since it is of type int.






    share|improve this answer













    Nullable types have special "boxing" rules; "boxing" is when a value-type is treated as object, as per your code. Unlike regular value-types, a nullable value-type is boxed either as null (regular null, no type), or as the non-nullable type (the T in T?). So: an int? is boxed as an int, not an int?. Then when you use OfType<int>() on it, you get all the values that are int, which is: the single value you passed in, since it is of type int.







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered 15 hours ago









    Marc GravellMarc Gravell

    792k19721582561




    792k19721582561












    • phew ok thank you for that explanaion. Is that C# basic knowledge?

      – Dr. Snail
      15 hours ago






    • 12





      @Dr.Snail "basic" is relative / subjective, and I'd wager that a good percentage of developers never have a need to know that nuance; it is useful context if you're dealing with boxing, though... and technically it isn't really C# knowledge, but rather: .NET knowledge (it would apply to all languages)

      – Marc Gravell
      15 hours ago












    • How would the query to obtain only int? from above items list will look like?

      – Sinatr
      15 hours ago







    • 4





      @Sinatr you can't - the list never contains int? - it only contains int because of the boxing rules on nullable types

      – Marc Gravell
      15 hours ago












    • Maybe I'm missing something but it returning 123 makes perfect sense to be. This long explanation does not. You added an int to a list and said give me all the integers in the list. The ? makes it so you can pass a null in the place of an int.

      – Kyle Johnson
      4 hours ago


















    • phew ok thank you for that explanaion. Is that C# basic knowledge?

      – Dr. Snail
      15 hours ago






    • 12





      @Dr.Snail "basic" is relative / subjective, and I'd wager that a good percentage of developers never have a need to know that nuance; it is useful context if you're dealing with boxing, though... and technically it isn't really C# knowledge, but rather: .NET knowledge (it would apply to all languages)

      – Marc Gravell
      15 hours ago












    • How would the query to obtain only int? from above items list will look like?

      – Sinatr
      15 hours ago







    • 4





      @Sinatr you can't - the list never contains int? - it only contains int because of the boxing rules on nullable types

      – Marc Gravell
      15 hours ago












    • Maybe I'm missing something but it returning 123 makes perfect sense to be. This long explanation does not. You added an int to a list and said give me all the integers in the list. The ? makes it so you can pass a null in the place of an int.

      – Kyle Johnson
      4 hours ago

















    phew ok thank you for that explanaion. Is that C# basic knowledge?

    – Dr. Snail
    15 hours ago





    phew ok thank you for that explanaion. Is that C# basic knowledge?

    – Dr. Snail
    15 hours ago




    12




    12





    @Dr.Snail "basic" is relative / subjective, and I'd wager that a good percentage of developers never have a need to know that nuance; it is useful context if you're dealing with boxing, though... and technically it isn't really C# knowledge, but rather: .NET knowledge (it would apply to all languages)

    – Marc Gravell
    15 hours ago






    @Dr.Snail "basic" is relative / subjective, and I'd wager that a good percentage of developers never have a need to know that nuance; it is useful context if you're dealing with boxing, though... and technically it isn't really C# knowledge, but rather: .NET knowledge (it would apply to all languages)

    – Marc Gravell
    15 hours ago














    How would the query to obtain only int? from above items list will look like?

    – Sinatr
    15 hours ago






    How would the query to obtain only int? from above items list will look like?

    – Sinatr
    15 hours ago





    4




    4





    @Sinatr you can't - the list never contains int? - it only contains int because of the boxing rules on nullable types

    – Marc Gravell
    15 hours ago






    @Sinatr you can't - the list never contains int? - it only contains int because of the boxing rules on nullable types

    – Marc Gravell
    15 hours ago














    Maybe I'm missing something but it returning 123 makes perfect sense to be. This long explanation does not. You added an int to a list and said give me all the integers in the list. The ? makes it so you can pass a null in the place of an int.

    – Kyle Johnson
    4 hours ago






    Maybe I'm missing something but it returning 123 makes perfect sense to be. This long explanation does not. You added an int to a list and said give me all the integers in the list. The ? makes it so you can pass a null in the place of an int.

    – Kyle Johnson
    4 hours ago














    4














    A nullable value type is boxed by the following rules:



    • If HasValue returns false, the null reference is produced.

    • If HasValue returns true, a value of the underlying value type T is
      boxed, not the instance of nullable.


    In your example second rule has been followed as you have value, e.g.
    var i = (object)(int?)123;






    share|improve this answer





























      4














      A nullable value type is boxed by the following rules:



      • If HasValue returns false, the null reference is produced.

      • If HasValue returns true, a value of the underlying value type T is
        boxed, not the instance of nullable.


      In your example second rule has been followed as you have value, e.g.
      var i = (object)(int?)123;






      share|improve this answer



























        4












        4








        4







        A nullable value type is boxed by the following rules:



        • If HasValue returns false, the null reference is produced.

        • If HasValue returns true, a value of the underlying value type T is
          boxed, not the instance of nullable.


        In your example second rule has been followed as you have value, e.g.
        var i = (object)(int?)123;






        share|improve this answer















        A nullable value type is boxed by the following rules:



        • If HasValue returns false, the null reference is produced.

        • If HasValue returns true, a value of the underlying value type T is
          boxed, not the instance of nullable.


        In your example second rule has been followed as you have value, e.g.
        var i = (object)(int?)123;







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited 10 hours ago

























        answered 14 hours ago









        JohnnyJohnny

        3,4251021




        3,4251021



























            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%2f55372675%2ftype-int-vs-type-int%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

            រឿង រ៉ូមេអូ និង ហ្ស៊ុយលីយេ សង្ខេបរឿង តួអង្គ បញ្ជីណែនាំ

            QGIS export composer to PDF scale the map [closed] Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Announcing the arrival of Valued Associate #679: Cesar Manara Unicorn Meta Zoo #1: Why another podcast?Print Composer QGIS 2.6, how to export image?QGIS 2.8.1 print composer won't export all OpenCycleMap base layer tilesSave Print/Map QGIS composer view as PNG/PDF using Python (without changing anything in visible layout)?Export QGIS Print Composer PDF with searchable text labelsQGIS Print Composer does not change from landscape to portrait orientation?How can I avoid map size and scale changes in print composer?Fuzzy PDF export in QGIS running on macSierra OSExport the legend into its 100% size using Print ComposerScale-dependent rendering in QGIS PDF output

            PDF-ში გადმოწერა სანავიგაციო მენიუproject page