As per CA1008 rule of FXCop Enums should have a default value of zero. Is this applicable for C#?

StackOverflow https://stackoverflow.com/questions/18825210

  •  28-06-2022
  •  | 
  •  

Domanda

Should this rule be applicable to C#?

The compiler gives error "Use of unassigned local variable" if we try to use the enum without explicitly setting a value?

The perspective being asked is the validity of the FxCop rule since I cannot use the default value of an enum.

public enum TraceLevel
{
    Off = 0,
    Error = 1,
    Warning = 2,
    Info = 3,
    Verbose = 4
}

class Program
{
    static void Main(string[] args)
    {
        TraceLevel traceLevelOptions;
        Console.WriteLine(traceLevelOptions.ToString());
        Console.ReadLine();
    }
}

Updated after getting the right answer. The following code should work:

public class SerializeMe
{
    public int Id { get; set; }
    public TraceLevel MyTrace { get; set; }
}

public enum TraceLevel
{
    Off = 0,
    Error = 1,
    Warning = 2,
    Info = 3,
    Verbose = 4
}

class Program
{
    static void Main(string[] args)
    {
        SerializeMe serializeMe = new SerializeMe();
        Console.WriteLine(serializeMe.MyTrace.ToString());
        Console.ReadLine();
    }
}
È stato utile?

Soluzione

The reason that enums should have a zero value is explained in the documentation for the Code Analysis error that relates to it:

http://msdn.microsoft.com/en-us/library/ms182149.aspx

CA1008: Enums should have zero value

The default value of an uninitialized enumeration, just like other value types, is zero. A non-flags−attributed enumeration should define a member that has the value of zero so that the default value is a valid value of the enumeration.

So the reason is that if, for example, you declare an enum field in a class or struct and do not initialise it, it will have the default value of zero. If there is no member of the enum with a zero value, you will in that (fairly common) situation have a enum field containing an invalid value.

There are also other instances where you can end up with a default-initialised enum field (e.g. during deserialization). You want to avoid a default-initialised enum field having an invalid value, hence the rule.

Altri suggerimenti

This isn't a FXCop error, it is a C# compiler error. In C# all the local variables must be initialized before being used.

TraceLevel traceLevelOptions = 0; // or TraceLevel.Error for example

Like for all the other types... If traceLevelOptions was an int, you would get the same error.

There is a loophole for struct types. You can assign them with a value or assign all their fields with a value, and they will be considered assigned. Note that this condition sometimes can't be satisfied if the struct has, for example, private fields.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top