How to use the Required attribute on Dictionary to prevent null values?2019 Community Moderator ElectionHow do I use IValidatableObject?How do you sort a dictionary by value?How do you give a C# Auto-Property a default value?Get int value from enum in C#How to loop through all enum values in C#?How do I generate a random int number?How to Sort a List<T> by a property in the objectReflection - get attribute name and value on propertyUpdate attributes to an object that is the value in a dictionaryConverting Dictionary<Int, Object> To Dictionary<Int, Object.Property> with lambdashow can we get value from dictionary if key is declare as nullable?

Describing a chess game in a novel

Generic TVP tradeoffs?

Bash - pair each line of file

Do native speakers use "ultima" and "proxima" frequently in spoken English?

Existence of a celestial body big enough for early civilization to be thought of as a second moon

Is there a term for accumulated dirt on the outside of your hands and feet?

What favor did Moody owe Dumbledore?

Why are there no stars visible in cislunar space?

Print a physical multiplication table

Should I be concerned about student access to a test bank?

Help rendering a complicated sum/product formula

How do hiring committees for research positions view getting "scooped"?

Help prove this basic trig identity please!

What are substitutions for coconut in curry?

Turning a hard to access nut?

Synchronized implementation of a bank account in Java

Is it possible to stack the damage done by the Absorb Elements spell?

Am I eligible for the Eurail Youth pass? I am 27.5 years old

Comment Box for Substitution Method of Integrals

World War I as a war of liberals against authoritarians?

What exactly term 'companion plants' means?

Writing in a Christian voice

Do US professors/group leaders only get a salary, but no group budget?

How does 取材で訪れた integrate into this sentence?



How to use the Required attribute on Dictionary to prevent null values?



2019 Community Moderator ElectionHow do I use IValidatableObject?How do you sort a dictionary by value?How do you give a C# Auto-Property a default value?Get int value from enum in C#How to loop through all enum values in C#?How do I generate a random int number?How to Sort a List<T> by a property in the objectReflection - get attribute name and value on propertyUpdate attributes to an object that is the value in a dictionaryConverting Dictionary<Int, Object> To Dictionary<Int, Object.Property> with lambdashow can we get value from dictionary if key is declare as nullable?










0















I have a class that contains a Dictionary<int, object> property that is marked as required. When I deserialize the data coming into the controller onto that class, the Required attribute works to prevent nulls from entering that property, but it does not stop nulls from entering the dictionary as a value given the key value pairs are formatted and passed in correctly.



Is there a way to have the Required attribute also prevent nulls from being values in the dictionary? Or is there another attribute that can be added to that property to accomplish this?



Or would the best way to solve this be to roll my own class that essentially consists of key-value pairs that I can mark both the key property and value property as Required? EX:



public class Example

[Required]
public int Key;

[Required]
public object Value;



And then just have an IEnumerable<Example> instead of Dictionary<int, object>?










share|improve this question






















  • Might be better to write your own attribute that does the checks you want.

    – Neil
    Mar 6 at 22:11











  • Possible duplicate of How do I use IValidatableObject?

    – Progman
    Mar 6 at 22:20















0















I have a class that contains a Dictionary<int, object> property that is marked as required. When I deserialize the data coming into the controller onto that class, the Required attribute works to prevent nulls from entering that property, but it does not stop nulls from entering the dictionary as a value given the key value pairs are formatted and passed in correctly.



Is there a way to have the Required attribute also prevent nulls from being values in the dictionary? Or is there another attribute that can be added to that property to accomplish this?



Or would the best way to solve this be to roll my own class that essentially consists of key-value pairs that I can mark both the key property and value property as Required? EX:



public class Example

[Required]
public int Key;

[Required]
public object Value;



And then just have an IEnumerable<Example> instead of Dictionary<int, object>?










share|improve this question






















  • Might be better to write your own attribute that does the checks you want.

    – Neil
    Mar 6 at 22:11











  • Possible duplicate of How do I use IValidatableObject?

    – Progman
    Mar 6 at 22:20













0












0








0








I have a class that contains a Dictionary<int, object> property that is marked as required. When I deserialize the data coming into the controller onto that class, the Required attribute works to prevent nulls from entering that property, but it does not stop nulls from entering the dictionary as a value given the key value pairs are formatted and passed in correctly.



Is there a way to have the Required attribute also prevent nulls from being values in the dictionary? Or is there another attribute that can be added to that property to accomplish this?



Or would the best way to solve this be to roll my own class that essentially consists of key-value pairs that I can mark both the key property and value property as Required? EX:



public class Example

[Required]
public int Key;

[Required]
public object Value;



And then just have an IEnumerable<Example> instead of Dictionary<int, object>?










share|improve this question














I have a class that contains a Dictionary<int, object> property that is marked as required. When I deserialize the data coming into the controller onto that class, the Required attribute works to prevent nulls from entering that property, but it does not stop nulls from entering the dictionary as a value given the key value pairs are formatted and passed in correctly.



Is there a way to have the Required attribute also prevent nulls from being values in the dictionary? Or is there another attribute that can be added to that property to accomplish this?



Or would the best way to solve this be to roll my own class that essentially consists of key-value pairs that I can mark both the key property and value property as Required? EX:



public class Example

[Required]
public int Key;

[Required]
public object Value;



And then just have an IEnumerable<Example> instead of Dictionary<int, object>?







c#






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 6 at 22:06









B. WitterB. Witter

313110




313110












  • Might be better to write your own attribute that does the checks you want.

    – Neil
    Mar 6 at 22:11











  • Possible duplicate of How do I use IValidatableObject?

    – Progman
    Mar 6 at 22:20

















  • Might be better to write your own attribute that does the checks you want.

    – Neil
    Mar 6 at 22:11











  • Possible duplicate of How do I use IValidatableObject?

    – Progman
    Mar 6 at 22:20
















Might be better to write your own attribute that does the checks you want.

– Neil
Mar 6 at 22:11





Might be better to write your own attribute that does the checks you want.

– Neil
Mar 6 at 22:11













Possible duplicate of How do I use IValidatableObject?

– Progman
Mar 6 at 22:20





Possible duplicate of How do I use IValidatableObject?

– Progman
Mar 6 at 22:20












2 Answers
2






active

oldest

votes


















0














The best I can think of is to have ISet<Example> (using a HashSet<Example>) with Example's GetHashCode and Equals methods overridden. That should satisfy your second desirable.
As for the [Required] attribute, you would have to write the code yourself to check if those properties are not null before adding it into the ISet<Example>. That may require some reflection logic.






share|improve this answer






























    0














    This is what I ended up going with, and it works exactly how I wanted Required to work.



    [AttributeUsage(AttributeTargets.Property)]
    public class DictionaryRequiredAttribute : ValidationAttribute

    public DictionaryRequiredAttribute() : base(() => "The 0 field is required and cannot contain null values.")

    public override bool IsValid(object value)

    if (value == null)

    return false;


    if (value is IDictionary dictValue)

    foreach (var key in dictValue.Keys)

    if (dictValue[key] == null)

    return false;




    return true;




    Based mainly on the implementation of the RequiredAttribute found here.






    share|improve this answer


















    • 1





      FYI: Just a little optimization. Instead of enumerating over the keys dictValue.Keys and looking up the values, you could directly enumerate over the values dictValue.Values (without requiring additional lookups) and condense the foreach loop into a simple and more readable Linq query: return dictValue.Values.All(v => v != null);

      – elgonzo
      Mar 7 at 0:03











    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%2f55032918%2fhow-to-use-the-required-attribute-on-dictionaryint-object-to-prevent-null-val%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









    0














    The best I can think of is to have ISet<Example> (using a HashSet<Example>) with Example's GetHashCode and Equals methods overridden. That should satisfy your second desirable.
    As for the [Required] attribute, you would have to write the code yourself to check if those properties are not null before adding it into the ISet<Example>. That may require some reflection logic.






    share|improve this answer



























      0














      The best I can think of is to have ISet<Example> (using a HashSet<Example>) with Example's GetHashCode and Equals methods overridden. That should satisfy your second desirable.
      As for the [Required] attribute, you would have to write the code yourself to check if those properties are not null before adding it into the ISet<Example>. That may require some reflection logic.






      share|improve this answer

























        0












        0








        0







        The best I can think of is to have ISet<Example> (using a HashSet<Example>) with Example's GetHashCode and Equals methods overridden. That should satisfy your second desirable.
        As for the [Required] attribute, you would have to write the code yourself to check if those properties are not null before adding it into the ISet<Example>. That may require some reflection logic.






        share|improve this answer













        The best I can think of is to have ISet<Example> (using a HashSet<Example>) with Example's GetHashCode and Equals methods overridden. That should satisfy your second desirable.
        As for the [Required] attribute, you would have to write the code yourself to check if those properties are not null before adding it into the ISet<Example>. That may require some reflection logic.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 6 at 22:16









        DandréDandré

        9621821




        9621821























            0














            This is what I ended up going with, and it works exactly how I wanted Required to work.



            [AttributeUsage(AttributeTargets.Property)]
            public class DictionaryRequiredAttribute : ValidationAttribute

            public DictionaryRequiredAttribute() : base(() => "The 0 field is required and cannot contain null values.")

            public override bool IsValid(object value)

            if (value == null)

            return false;


            if (value is IDictionary dictValue)

            foreach (var key in dictValue.Keys)

            if (dictValue[key] == null)

            return false;




            return true;




            Based mainly on the implementation of the RequiredAttribute found here.






            share|improve this answer


















            • 1





              FYI: Just a little optimization. Instead of enumerating over the keys dictValue.Keys and looking up the values, you could directly enumerate over the values dictValue.Values (without requiring additional lookups) and condense the foreach loop into a simple and more readable Linq query: return dictValue.Values.All(v => v != null);

              – elgonzo
              Mar 7 at 0:03
















            0














            This is what I ended up going with, and it works exactly how I wanted Required to work.



            [AttributeUsage(AttributeTargets.Property)]
            public class DictionaryRequiredAttribute : ValidationAttribute

            public DictionaryRequiredAttribute() : base(() => "The 0 field is required and cannot contain null values.")

            public override bool IsValid(object value)

            if (value == null)

            return false;


            if (value is IDictionary dictValue)

            foreach (var key in dictValue.Keys)

            if (dictValue[key] == null)

            return false;




            return true;




            Based mainly on the implementation of the RequiredAttribute found here.






            share|improve this answer


















            • 1





              FYI: Just a little optimization. Instead of enumerating over the keys dictValue.Keys and looking up the values, you could directly enumerate over the values dictValue.Values (without requiring additional lookups) and condense the foreach loop into a simple and more readable Linq query: return dictValue.Values.All(v => v != null);

              – elgonzo
              Mar 7 at 0:03














            0












            0








            0







            This is what I ended up going with, and it works exactly how I wanted Required to work.



            [AttributeUsage(AttributeTargets.Property)]
            public class DictionaryRequiredAttribute : ValidationAttribute

            public DictionaryRequiredAttribute() : base(() => "The 0 field is required and cannot contain null values.")

            public override bool IsValid(object value)

            if (value == null)

            return false;


            if (value is IDictionary dictValue)

            foreach (var key in dictValue.Keys)

            if (dictValue[key] == null)

            return false;




            return true;




            Based mainly on the implementation of the RequiredAttribute found here.






            share|improve this answer













            This is what I ended up going with, and it works exactly how I wanted Required to work.



            [AttributeUsage(AttributeTargets.Property)]
            public class DictionaryRequiredAttribute : ValidationAttribute

            public DictionaryRequiredAttribute() : base(() => "The 0 field is required and cannot contain null values.")

            public override bool IsValid(object value)

            if (value == null)

            return false;


            if (value is IDictionary dictValue)

            foreach (var key in dictValue.Keys)

            if (dictValue[key] == null)

            return false;




            return true;




            Based mainly on the implementation of the RequiredAttribute found here.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Mar 6 at 23:25









            B. WitterB. Witter

            313110




            313110







            • 1





              FYI: Just a little optimization. Instead of enumerating over the keys dictValue.Keys and looking up the values, you could directly enumerate over the values dictValue.Values (without requiring additional lookups) and condense the foreach loop into a simple and more readable Linq query: return dictValue.Values.All(v => v != null);

              – elgonzo
              Mar 7 at 0:03













            • 1





              FYI: Just a little optimization. Instead of enumerating over the keys dictValue.Keys and looking up the values, you could directly enumerate over the values dictValue.Values (without requiring additional lookups) and condense the foreach loop into a simple and more readable Linq query: return dictValue.Values.All(v => v != null);

              – elgonzo
              Mar 7 at 0:03








            1




            1





            FYI: Just a little optimization. Instead of enumerating over the keys dictValue.Keys and looking up the values, you could directly enumerate over the values dictValue.Values (without requiring additional lookups) and condense the foreach loop into a simple and more readable Linq query: return dictValue.Values.All(v => v != null);

            – elgonzo
            Mar 7 at 0:03






            FYI: Just a little optimization. Instead of enumerating over the keys dictValue.Keys and looking up the values, you could directly enumerate over the values dictValue.Values (without requiring additional lookups) and condense the foreach loop into a simple and more readable Linq query: return dictValue.Values.All(v => v != null);

            – elgonzo
            Mar 7 at 0:03


















            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%2f55032918%2fhow-to-use-the-required-attribute-on-dictionaryint-object-to-prevent-null-val%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

            1928 у кіно

            Захаров Федір Захарович

            Ель Греко