locked
Data Annotation to set Default Value for an enum property RRS feed

  • Question

  • HEre is enum:

    public enum Status
        {
            New,
            Broken,
            Repaired
        }

    My class:

    public class Car
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public string Address { get; set; }
            //Set the default value to Broken using DataAnnotation
            public Status Status { get; set; }
        }
    How can I set the default value for Status property using Data Annotations?



    Monday, June 2, 2014 2:14 PM

Answers

  • Hello, 

    Enums are numeric values (int). So the default value is 0.

    In your code default value is  "New" because it's the first declared.

    You can set the value for each enum value like this : 

    public enum Status
        {
            New = 1,
            Broken = 0,
            Repaired = 2
        }

    Or you can set the defautl value for the car in the constructor.

    There's no other issue to do this.

    Regards. 


    Kevin BEAUGRAND, Modis FRANCE
    Merci de bien vouloir "Marquer comme réponse", les réponses qui ont résolu votre problème.

    • Marked as answer by Fred Bao Thursday, June 12, 2014 6:38 AM
    Monday, June 2, 2014 2:21 PM

All replies

  • Hello, 

    Enums are numeric values (int). So the default value is 0.

    In your code default value is  "New" because it's the first declared.

    You can set the value for each enum value like this : 

    public enum Status
        {
            New = 1,
            Broken = 0,
            Repaired = 2
        }

    Or you can set the defautl value for the car in the constructor.

    There's no other issue to do this.

    Regards. 


    Kevin BEAUGRAND, Modis FRANCE
    Merci de bien vouloir "Marquer comme réponse", les réponses qui ont résolu votre problème.

    • Marked as answer by Fred Bao Thursday, June 12, 2014 6:38 AM
    Monday, June 2, 2014 2:21 PM
  • Did you mean? :
    public class Car
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public string Address { get; set; }
            
    [DefaultValue((int)Status.Broken)]
    
            public Status Status { get; set; }
        }
    Thursday, May 31, 2018 5:57 AM