Default Value of a dictionary and FirstOrDefault() in LINQ mismatch












0















Why default value of a dictionary class is not same as default value returned by FirstOrDefault using LINQ?



Dictionary<Mode, string> myDict = new Dictionary<Mode, string>() { { Mode.First, "ValueFirst" }, { Mode.Second, "ValueSecond" }, { Mode.Third, "ValueThird" }, { Mode.Forth, "ValueForth" } };
var r1 = myDict.Where(d => d.Value == "Do not exist").FirstOrDefault();
var r2 = default(Dictionary<Mode, string>);


Here Mode is an enum. As a result, r1 is a key-value pair with default values, but r2 is null. Why?










share|improve this question




















  • 2





    Because FirstOrDefault() returns a KeyValuePair. Not a dictionary.

    – Gert Arnold
    Nov 20 '18 at 22:40











  • Or, it can return default(KeyValuePair), which is null - always watch out for nulls on FirstOrDefault(). That's related to your second question (about r2). If you are working with a reference type (like a Dictionary), then default(YourReferenceTypeGoesHere) is null - it's always null. If you use default on a value type, then it's the zero-ish value, but for reference types, it's always null

    – Flydog57
    Nov 20 '18 at 22:44








  • 1





    KeyValuePair<,> is a struct, it can never be null. Unless we are talking about Nullable<KeyValuePair<,>>` which is another type.

    – Xiaoy312
    Nov 20 '18 at 22:47











  • @Xiaoy312: Ooops! Didn't look it up. Makes sense for it to be a value type. Thanks! I've spent a lot of time over the past year cleaning up messes where co-workers called Whatever().FirstOrDefault() and then used the results without a null-check. It's one of my go to code review issues now.

    – Flydog57
    Nov 20 '18 at 22:48













  • var r1 = myDict.Where(d => d.Value == "Do not exist").FirstOrDefault(); This is a terrible idea. You can't distinguish whether there was really an entry there or not. If you want to know whether an entry was there you must use ContainsKey or TryGetValue. Or use (worse) var r1 = myDict.Where(d => d.Value == "Do not exist").Cast<KeyValuePair<Mode, string>?>.FirstOrDefault(); so you can get null (which clearly means 'it wasn't there').

    – mjwills
    Nov 20 '18 at 23:02


















0















Why default value of a dictionary class is not same as default value returned by FirstOrDefault using LINQ?



Dictionary<Mode, string> myDict = new Dictionary<Mode, string>() { { Mode.First, "ValueFirst" }, { Mode.Second, "ValueSecond" }, { Mode.Third, "ValueThird" }, { Mode.Forth, "ValueForth" } };
var r1 = myDict.Where(d => d.Value == "Do not exist").FirstOrDefault();
var r2 = default(Dictionary<Mode, string>);


Here Mode is an enum. As a result, r1 is a key-value pair with default values, but r2 is null. Why?










share|improve this question




















  • 2





    Because FirstOrDefault() returns a KeyValuePair. Not a dictionary.

    – Gert Arnold
    Nov 20 '18 at 22:40











  • Or, it can return default(KeyValuePair), which is null - always watch out for nulls on FirstOrDefault(). That's related to your second question (about r2). If you are working with a reference type (like a Dictionary), then default(YourReferenceTypeGoesHere) is null - it's always null. If you use default on a value type, then it's the zero-ish value, but for reference types, it's always null

    – Flydog57
    Nov 20 '18 at 22:44








  • 1





    KeyValuePair<,> is a struct, it can never be null. Unless we are talking about Nullable<KeyValuePair<,>>` which is another type.

    – Xiaoy312
    Nov 20 '18 at 22:47











  • @Xiaoy312: Ooops! Didn't look it up. Makes sense for it to be a value type. Thanks! I've spent a lot of time over the past year cleaning up messes where co-workers called Whatever().FirstOrDefault() and then used the results without a null-check. It's one of my go to code review issues now.

    – Flydog57
    Nov 20 '18 at 22:48













  • var r1 = myDict.Where(d => d.Value == "Do not exist").FirstOrDefault(); This is a terrible idea. You can't distinguish whether there was really an entry there or not. If you want to know whether an entry was there you must use ContainsKey or TryGetValue. Or use (worse) var r1 = myDict.Where(d => d.Value == "Do not exist").Cast<KeyValuePair<Mode, string>?>.FirstOrDefault(); so you can get null (which clearly means 'it wasn't there').

    – mjwills
    Nov 20 '18 at 23:02
















0












0








0








Why default value of a dictionary class is not same as default value returned by FirstOrDefault using LINQ?



Dictionary<Mode, string> myDict = new Dictionary<Mode, string>() { { Mode.First, "ValueFirst" }, { Mode.Second, "ValueSecond" }, { Mode.Third, "ValueThird" }, { Mode.Forth, "ValueForth" } };
var r1 = myDict.Where(d => d.Value == "Do not exist").FirstOrDefault();
var r2 = default(Dictionary<Mode, string>);


Here Mode is an enum. As a result, r1 is a key-value pair with default values, but r2 is null. Why?










share|improve this question
















Why default value of a dictionary class is not same as default value returned by FirstOrDefault using LINQ?



Dictionary<Mode, string> myDict = new Dictionary<Mode, string>() { { Mode.First, "ValueFirst" }, { Mode.Second, "ValueSecond" }, { Mode.Third, "ValueThird" }, { Mode.Forth, "ValueForth" } };
var r1 = myDict.Where(d => d.Value == "Do not exist").FirstOrDefault();
var r2 = default(Dictionary<Mode, string>);


Here Mode is an enum. As a result, r1 is a key-value pair with default values, but r2 is null. Why?







c# linq default-value






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 21 '18 at 0:47







Mayank Garg

















asked Nov 20 '18 at 22:36









Mayank GargMayank Garg

63




63








  • 2





    Because FirstOrDefault() returns a KeyValuePair. Not a dictionary.

    – Gert Arnold
    Nov 20 '18 at 22:40











  • Or, it can return default(KeyValuePair), which is null - always watch out for nulls on FirstOrDefault(). That's related to your second question (about r2). If you are working with a reference type (like a Dictionary), then default(YourReferenceTypeGoesHere) is null - it's always null. If you use default on a value type, then it's the zero-ish value, but for reference types, it's always null

    – Flydog57
    Nov 20 '18 at 22:44








  • 1





    KeyValuePair<,> is a struct, it can never be null. Unless we are talking about Nullable<KeyValuePair<,>>` which is another type.

    – Xiaoy312
    Nov 20 '18 at 22:47











  • @Xiaoy312: Ooops! Didn't look it up. Makes sense for it to be a value type. Thanks! I've spent a lot of time over the past year cleaning up messes where co-workers called Whatever().FirstOrDefault() and then used the results without a null-check. It's one of my go to code review issues now.

    – Flydog57
    Nov 20 '18 at 22:48













  • var r1 = myDict.Where(d => d.Value == "Do not exist").FirstOrDefault(); This is a terrible idea. You can't distinguish whether there was really an entry there or not. If you want to know whether an entry was there you must use ContainsKey or TryGetValue. Or use (worse) var r1 = myDict.Where(d => d.Value == "Do not exist").Cast<KeyValuePair<Mode, string>?>.FirstOrDefault(); so you can get null (which clearly means 'it wasn't there').

    – mjwills
    Nov 20 '18 at 23:02
















  • 2





    Because FirstOrDefault() returns a KeyValuePair. Not a dictionary.

    – Gert Arnold
    Nov 20 '18 at 22:40











  • Or, it can return default(KeyValuePair), which is null - always watch out for nulls on FirstOrDefault(). That's related to your second question (about r2). If you are working with a reference type (like a Dictionary), then default(YourReferenceTypeGoesHere) is null - it's always null. If you use default on a value type, then it's the zero-ish value, but for reference types, it's always null

    – Flydog57
    Nov 20 '18 at 22:44








  • 1





    KeyValuePair<,> is a struct, it can never be null. Unless we are talking about Nullable<KeyValuePair<,>>` which is another type.

    – Xiaoy312
    Nov 20 '18 at 22:47











  • @Xiaoy312: Ooops! Didn't look it up. Makes sense for it to be a value type. Thanks! I've spent a lot of time over the past year cleaning up messes where co-workers called Whatever().FirstOrDefault() and then used the results without a null-check. It's one of my go to code review issues now.

    – Flydog57
    Nov 20 '18 at 22:48













  • var r1 = myDict.Where(d => d.Value == "Do not exist").FirstOrDefault(); This is a terrible idea. You can't distinguish whether there was really an entry there or not. If you want to know whether an entry was there you must use ContainsKey or TryGetValue. Or use (worse) var r1 = myDict.Where(d => d.Value == "Do not exist").Cast<KeyValuePair<Mode, string>?>.FirstOrDefault(); so you can get null (which clearly means 'it wasn't there').

    – mjwills
    Nov 20 '18 at 23:02










2




2





Because FirstOrDefault() returns a KeyValuePair. Not a dictionary.

– Gert Arnold
Nov 20 '18 at 22:40





Because FirstOrDefault() returns a KeyValuePair. Not a dictionary.

– Gert Arnold
Nov 20 '18 at 22:40













Or, it can return default(KeyValuePair), which is null - always watch out for nulls on FirstOrDefault(). That's related to your second question (about r2). If you are working with a reference type (like a Dictionary), then default(YourReferenceTypeGoesHere) is null - it's always null. If you use default on a value type, then it's the zero-ish value, but for reference types, it's always null

– Flydog57
Nov 20 '18 at 22:44







Or, it can return default(KeyValuePair), which is null - always watch out for nulls on FirstOrDefault(). That's related to your second question (about r2). If you are working with a reference type (like a Dictionary), then default(YourReferenceTypeGoesHere) is null - it's always null. If you use default on a value type, then it's the zero-ish value, but for reference types, it's always null

– Flydog57
Nov 20 '18 at 22:44






1




1





KeyValuePair<,> is a struct, it can never be null. Unless we are talking about Nullable<KeyValuePair<,>>` which is another type.

– Xiaoy312
Nov 20 '18 at 22:47





KeyValuePair<,> is a struct, it can never be null. Unless we are talking about Nullable<KeyValuePair<,>>` which is another type.

– Xiaoy312
Nov 20 '18 at 22:47













@Xiaoy312: Ooops! Didn't look it up. Makes sense for it to be a value type. Thanks! I've spent a lot of time over the past year cleaning up messes where co-workers called Whatever().FirstOrDefault() and then used the results without a null-check. It's one of my go to code review issues now.

– Flydog57
Nov 20 '18 at 22:48







@Xiaoy312: Ooops! Didn't look it up. Makes sense for it to be a value type. Thanks! I've spent a lot of time over the past year cleaning up messes where co-workers called Whatever().FirstOrDefault() and then used the results without a null-check. It's one of my go to code review issues now.

– Flydog57
Nov 20 '18 at 22:48















var r1 = myDict.Where(d => d.Value == "Do not exist").FirstOrDefault(); This is a terrible idea. You can't distinguish whether there was really an entry there or not. If you want to know whether an entry was there you must use ContainsKey or TryGetValue. Or use (worse) var r1 = myDict.Where(d => d.Value == "Do not exist").Cast<KeyValuePair<Mode, string>?>.FirstOrDefault(); so you can get null (which clearly means 'it wasn't there').

– mjwills
Nov 20 '18 at 23:02







var r1 = myDict.Where(d => d.Value == "Do not exist").FirstOrDefault(); This is a terrible idea. You can't distinguish whether there was really an entry there or not. If you want to know whether an entry was there you must use ContainsKey or TryGetValue. Or use (worse) var r1 = myDict.Where(d => d.Value == "Do not exist").Cast<KeyValuePair<Mode, string>?>.FirstOrDefault(); so you can get null (which clearly means 'it wasn't there').

– mjwills
Nov 20 '18 at 23:02














1 Answer
1






active

oldest

votes


















-1














Use default(KeyValuePair<,>) to check for default value:



var kvp = dict.FirstOrDefault(...);
if (default(KeyValuePair<Mode, string>).Equals(kvp))


Alternatively, you could use an extension method here:



public static class KeyValuePairExtensions
{
public static bool IsDefault<TKey, TValue>(this KeyValuePair<TKey, TValue> kvp) => default(KeyValuePair<Mode, string>).Equals(kvp);
}

// usage
var kvp = dict.FirstOrDefault(...);
if (kvp.IsDefault())





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%2f53402621%2fdefault-value-of-a-dictionary-and-firstordefault-in-linq-mismatch%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    -1














    Use default(KeyValuePair<,>) to check for default value:



    var kvp = dict.FirstOrDefault(...);
    if (default(KeyValuePair<Mode, string>).Equals(kvp))


    Alternatively, you could use an extension method here:



    public static class KeyValuePairExtensions
    {
    public static bool IsDefault<TKey, TValue>(this KeyValuePair<TKey, TValue> kvp) => default(KeyValuePair<Mode, string>).Equals(kvp);
    }

    // usage
    var kvp = dict.FirstOrDefault(...);
    if (kvp.IsDefault())





    share|improve this answer




























      -1














      Use default(KeyValuePair<,>) to check for default value:



      var kvp = dict.FirstOrDefault(...);
      if (default(KeyValuePair<Mode, string>).Equals(kvp))


      Alternatively, you could use an extension method here:



      public static class KeyValuePairExtensions
      {
      public static bool IsDefault<TKey, TValue>(this KeyValuePair<TKey, TValue> kvp) => default(KeyValuePair<Mode, string>).Equals(kvp);
      }

      // usage
      var kvp = dict.FirstOrDefault(...);
      if (kvp.IsDefault())





      share|improve this answer


























        -1












        -1








        -1







        Use default(KeyValuePair<,>) to check for default value:



        var kvp = dict.FirstOrDefault(...);
        if (default(KeyValuePair<Mode, string>).Equals(kvp))


        Alternatively, you could use an extension method here:



        public static class KeyValuePairExtensions
        {
        public static bool IsDefault<TKey, TValue>(this KeyValuePair<TKey, TValue> kvp) => default(KeyValuePair<Mode, string>).Equals(kvp);
        }

        // usage
        var kvp = dict.FirstOrDefault(...);
        if (kvp.IsDefault())





        share|improve this answer













        Use default(KeyValuePair<,>) to check for default value:



        var kvp = dict.FirstOrDefault(...);
        if (default(KeyValuePair<Mode, string>).Equals(kvp))


        Alternatively, you could use an extension method here:



        public static class KeyValuePairExtensions
        {
        public static bool IsDefault<TKey, TValue>(this KeyValuePair<TKey, TValue> kvp) => default(KeyValuePair<Mode, string>).Equals(kvp);
        }

        // usage
        var kvp = dict.FirstOrDefault(...);
        if (kvp.IsDefault())






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 20 '18 at 22:53









        Xiaoy312Xiaoy312

        11.2k12133




        11.2k12133






























            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%2f53402621%2fdefault-value-of-a-dictionary-and-firstordefault-in-linq-mismatch%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

            "Incorrect syntax near the keyword 'ON'. (on update cascade, on delete cascade,)

            Alcedinidae

            Origin of the phrase “under your belt”?