1

I have the following code in a User Control:

public partial class MyControl : System.Web.UI.UserControl
{    
    public Enums.InformationSubCategory SubCategory { get; set; }

    ...omitted code
}

Enums.InformationSubCategory is an enum I have defined elsewhere, with the idea being that I can do this:

Example 1. <my:MyControl runat="server" SubCategory="Food" ...... />
Example 2. <my:MyControl runat="server" ...... />

If I don't specify a value at all for SubCategory, what will the value of SubCategory be in the code-behind for MyControl? Is it null or does a default value get applied to it? I noticed that with int properties, it defaults to zero.

3 Answers 3

2

Fields get initialized to default(T). The easy way to remember what the default value of some type is that it corresponds to binary zero in the obvious implementation.

For an enum this means that the underlying integer type is set to 0. By default this corresponds to the first value defined in the enum.

That's why it's common to name the first value in an enum None.

Sign up to request clarification or add additional context in comments.

4 Comments

'the first value defined in the enum' - assuming no explicit value has been assigned, ie. enum Foo { Bar = 1, None = 0 }
Yes, that's why I said "By default".
@CodeInChaos What if I have assigned non-zero integers to all of the enum members?
Then it will still become 0. It's an unnamed value. Enums can have all values of the underlying integer type, even those that have no name.
0

The default underlying type of the enumeration elements is int. By default, the first enumerator has the value 0, and the value of each successive enumerator is increased by 1. For example:

enum Days {Sat, Sun, Mon, Tue, Wed, Thu, Fri};

In this enumeration, Sat is 0, Sun is 1, Mon is 2, and so forth. Enumerators can have initializers to override the default values.

enum Days {Sat=1, Sun, Mon, Tue, Wed, Thu, Fri};

In this enumeration, the sequence of elements is forced to start from 1 instead of 0.

1 Comment

Great explanation on enums but doesn't answer the question!
0

It will be 0, as your enum is by default based on Int32.

3 Comments

It will be 0 but it could be a byte or short.
@Henk - That's why I said 'by default'.
Yes, you're right. I thought the compiler was free to choose. msdn.microsoft.com/en-us/library/cc138362.aspx

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.