Click to Rate and Give Feedback
MSDN
MSDN Library
.NET Development
Previous Versions
.NET Framework 2.0
Collapse All/Expand All Collapse All
This page is specific to
Microsoft Visual Studio 2005/.NET Framework 2.0

Other versions are also available for the following:
InvalidEnumArgumentException Class
The exception thrown when using invalid arguments that are enumerators.

Namespace: System.ComponentModel
Assembly: System (in system.dll)

Visual Basic (Declaration)
<SerializableAttribute> _
Public Class InvalidEnumArgumentException
    Inherits ArgumentException
Visual Basic (Usage)
Dim instance As InvalidEnumArgumentException
C#
[SerializableAttribute] 
public class InvalidEnumArgumentException : ArgumentException
C++
[SerializableAttribute] 
public ref class InvalidEnumArgumentException : public ArgumentException
J#
/** @attribute SerializableAttribute() */ 
public class InvalidEnumArgumentException extends ArgumentException
JScript
SerializableAttribute 
public class InvalidEnumArgumentException extends ArgumentException
XAML
Not applicable.

This exception is thrown if you pass an invalid enumeration value to a method or when setting a property.

NoteNote:

The HostProtectionAttribute attribute applied to this class has the following Resources property value: SharedState. The HostProtectionAttribute does not affect desktop applications (which are typically started by double-clicking an icon, typing a command, or entering a URL in a browser). For more information, see the HostProtectionAttribute class or SQL Server Programming and Host Protection Attributes.

The following code example shows how to catch an InvalidEnumArgumentException exception and interpret its content. The example attempts to pass an invalid enumeration value (MessageBoxButtons) through casting, as the MessageBox.Show method's third argument. Upon catching the exception, the example fetches the respective error message, the invalid parameter, stack trace, and origin of the exception.

Visual Basic
Try
    ' Attempts to pass an invalid enum value (MessageBoxButtons) to the Show method
    Dim myButton As MessageBoxButtons
    myButton = CType(123, MessageBoxButtons)
    MessageBox.Show("This is a message", "This is the Caption", myButton)
Catch invE As System.ComponentModel.InvalidEnumArgumentException
    Console.WriteLine(invE.Message)
    Console.WriteLine(invE.ParamName)
    Console.WriteLine(invE.StackTrace)
    Console.WriteLine(invE.Source)
End Try
C#
try 
{
// Attempts to pass an invalid enum value (MessageBoxButtons) to the Show method
    MessageBoxButtons myButton= (MessageBoxButtons) 123;
    MessageBox.Show("This is a message","This is the Caption",myButton);
}
catch(InvalidEnumArgumentException invE) 
{
    Console.WriteLine(invE.Message);
    Console.WriteLine(invE.ParamName);
    Console.WriteLine(invE.StackTrace);
    Console.WriteLine(invE.Source);
}
C++
try
{
   //Attempting to pass an invalid enum value (MessageBoxButtons) to the Show method
   MessageBoxButtons myButton = (MessageBoxButtons)123; // to fix use System::Windows::Forms::DialogResult::OK;

   MessageBox::Show( this,  "This is a message",  "This is the Caption", myButton );
}
catch ( InvalidEnumArgumentException^ invE ) 
{
   Console::WriteLine( invE->Message );
   Console::WriteLine( invE->ParamName );
   Console::WriteLine( invE->StackTrace );
   Console::WriteLine( invE->Source );
}
J#
try {
    // Attempts to pass an invalid enum value (MessageBoxButtons)
    // to the Show method
    MessageBoxButtons myButton = (MessageBoxButtons)123;
    MessageBox.Show("This is a message", 
        "This is the Caption", myButton);
}
catch (InvalidEnumArgumentException invE) {
    Console.WriteLine(invE.get_Message());
    Console.WriteLine(invE.get_ParamName());
    Console.WriteLine(invE.get_StackTrace());
    Console.WriteLine(invE.get_Source());
}
System.Object
   System.Exception
     System.SystemException
       System.ArgumentException
        System.ComponentModel.InvalidEnumArgumentException
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Windows 98, Windows Server 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The Microsoft .NET Framework 3.0 is supported on Windows Vista, Microsoft Windows XP SP2, and Windows Server 2003 SP1.

.NET Framework

Supported in: 3.0, 2.0, 1.1, 1.0
Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
You do not need to pass a message to the constructor      David M. Kean - MSFT   |   Edit   |   Show History

Typically InvalidEnumArgumentException is thrown to indicate that a value passed for a enum parameter is not a valid value for that enum's type.

You do not need to pass a message to one of InvalidEnumArgumentException's constructors that takes one; passing it the parameter name, the invalid parameter and the type of the enum causes it construct one for you along the lines of 'The value of argument '{argumentName}' ({invalidValue}) is invalid for Enum type '{enumClass}'.'

Tags What's this?: Add a tag
Flag as ContentBug
Techniques for validating an enum parameter      David M. Kean - MSFT   |   Edit   |   Show History

As shown in the example above, it is possible to pass a value outside of the range of an enum's allowed values. Due to this, it is advised that you validate all enum parameters. There are a number of ways to do this, with some techniques better than others. The following example shows three different methods.

C#:

public enum WeekDay
{
    Sunday = 0,
    Monday = 1,
    Tuesday = 2,
    Wednesday = 3,
    Thursday = 4,
    Friday = 5,
    Saturday = 6,
}
 
public static class WeekDayHelper
{
    public static bool IsWorkDay1(WeekDay day)
    {
        if (day < WeekDay.Sunday || day > WeekDay.Saturday)
            throw new InvalidEnumArgumentException("day", (int)day, typeof(WeekDay));
   
        return day >= WeekDay.Monday && day <= WeekDay.Friday;
    }
 
    public static bool IsWorkDay2(WeekDay day)
    {
        switch (day)
        {
            case WeekDay.Sunday:
            case WeekDay.Saturday:
                return false;
 
            case WeekDay.Monday:
            case WeekDay.Tuesday:
            case WeekDay.Wednesday:
            case WeekDay.Thursday:
            case WeekDay.Friday:
                return true;
        }
 
        throw new InvalidEnumArgumentException("day", (int)day, typeof(WeekDay));
    }
 
    // Not recommended
    public static bool IsWorkDay3(WeekDay day)
    {
        if (!Enum.IsDefined(typeof(WeekDay), day))
            throw new InvalidEnumArgumentException("day", (int)day, typeof(WeekDay));
        
        return day >= WeekDay.Monday && day <= WeekDay.Friday;
    }
}

 

In the first method, IsWorkDay1, the enum parameter is validated to ensure that it equal to or between the lowest valid value and the highest valid value. This has the benefit of being the cheapest, however, if during development of a product and the values of the enum changes, it could validate the values incorrectly.

The second method, IsWorkDay2, uses a switch statement to validate day. This doesn't suffer from the same problem as IsWorkDay1 (if the enum is in the same assembly) and it becomes an easy way to validate, if later in the method you are going to switch on the parameter anyway.

Although IsWorkDay3 is the simplest, it is the least recommended. Enum.IsDefined uses Reflection and rarely touched metadata to determine the valid values of the enum, and because of this, is very expensive in comparision to the other two techniques. It also suffers from a versioning issue, which is explained here: http://blogs.msdn.com/kcwalina/archive/2004/05/18/134208.aspx

Tags What's this?: Add a tag
Flag as ContentBug
Is defined in System.dll and not mscorlib.dll      David M. Kean - MSFT ... marcelvr   |   Edit   |   Show History
Unfortunately, as InvalidEnumArgumentException is defined in System.dll and not mscorlib.dll, the latter does not throw it when an invalid enum argument is passed to a member, but instead throws ArgumentException or ArgumentOutOfRangeException. This inconsistancy however, usually does not present a problem, as this exception when thrown, typically indicates a bug in the caller and is rarely caught within a catch clause.
Tags What's this?: Add a tag
Flag as ContentBug
Processing
© 2009 Microsoft Corporation. All rights reserved. Terms of Use | Trademarks | Privacy Statement | Site Feedback
Page view tracker