Haseeb Ahmed
Haseeb Ahmed

Reputation: 243

How can add new enumeration in system enums?

How can I add new enumeration in system enums?

I want to add a new button-type (None=6) in MessageBoxButton enum:

Default list is:

MessageBoxButton.Ok=0
MessageBoxButton.Cancel=1
MessageBoxButton.AbortRetryIgnore=2
MessageBoxButton.YesNoCancel=3
MessageBoxButton.YesNo=4
MessageBoxButton.RetryCancel=5

I want to add a new member:

MessageBoxButton.None=6

Upvotes: 0

Views: 432

Answers (1)

Jon Hanna
Jon Hanna

Reputation: 113272

To actually have the enum changed you would need to file a change request, convince people (different people for the .NET Core and .NET Framework changes) that it's a good idea without significant backwards compatibility issues, and then wait until the change was made and use the new framework version.

This obviously isn't a practical short-term measure.

To have an extra value on an enum all you need to do is use it and look for it:

public static MessageBoxButton ReturnExtendedValue()
{
    return (MessageBoxButton)6;
}

public static bool IsMessageBoxButtonThePrivatelyUsedExtraValue(MessageBoxButton value)
{
    return value == (MessageBoxButton)6;
}

void Main()
{
    Console.WriteLine(
        IsMessageBoxButtonThePrivatelyUsedExtraValue(
            ReturnExtendedValue())); // Prints "True"
}

Generally, enum does not limit values to those defined by the enum, it just gives some values meaning. You are free to apply your own meanings to values outside the defined range.

Generally also though, this isn't a great idea. For one thing, you don't know that the new value you've assigned won't be used in a future version of the framework. You are likely better off separating the states, with a bool return for whether there was a button press or not and an out MessageBoxButton indicating what it was if there was one.

If you are going to use values outside the defined range, using negative values is likely (but not guaranteed) to have fewer forwards compatibility issues.

Upvotes: 1

Related Questions