strongmmc
strongmmc

Reputation: 315

.NET Enum - decorate EnumValue to be used as default value

Lets say for maintenance and DataContract serialization i need to add the default value 0 to an existing enum where it wasn't present.

public enum ExistingEnum { Value1 = 1, Value2 = 2, Value3 = 3 }

Becomes:

public enum ExistingEnum { None = 0, Value1 = 1, Value2 = 2, Value3 = 3 }

All the properties that relied on taking the Value1 as default value are now causing a chain of problems and related Exceptions. Is there a way, like an attribute, to impose Value1 as the default value, again? Something similar to:

public enum ExistingEnum
{
    None = 0,
    [Default] Value1 = 1,
    Value2 = 2,
    Value3 = 3
 }

Thanks in advance

Upvotes: 2

Views: 1899

Answers (2)

strongmmc
strongmmc

Reputation: 315

I should stop asking things on StackOverflow. Everytime I try to keep it simple and easy to understand, it seems nobody reads the the question. I asked one simple thing, which was answered by a MSDN page I wasn't able to find in the past 45 minutes, but that I found now: System.ComponentModel.DefaultValueAttribute

If I have an enum that goes from 0 to 3 and I need 1 to be taken as default value when instantiating a variable of that enum type, I need to use this attribute class.

[DefaultValue(typeof(ExistingEnum),"Value1 ")]
public enum ExistingEnum
{
    None = 0,
    Value1 = 1,
    Value2 = 2,
    Value3 = 3
}

Thanks anyway to everyone who spent its time answering this stupid question

Upvotes: 5

jdweng
jdweng

Reputation: 34429

Try this

      public enum Existing
       {
           Default = 1,
           None = 0,
           Value1 = 1,
           Value2 = 2,
           Value3 = 3
       }

Upvotes: -1

Related Questions