Skip to Main Content Skip to Search
Product Documentation

.NET Enumerations in MATLAB

Overview of .NET Enumerations

MATLAB allows you to work with .NET enumerations using features of the MATLAB enumeration class and some features unique to the .NET Framework.

Terms you should know:

Enumerations contain the following information:

In this topic, the term enumeration refers to a .NET enumeration.

Some basic tasks described in this topic:

Using the NetDocEnum Example Assembly

Some of the examples in this topic use the System.DayOfWeek enumeration, which is part of the .NET Framework. The C# example NetDocEnum.cs, in the matlabroot/extern/examples/NET/NetSample folder, defines enumerations used in other examples. To see the code, open the file in MATLAB Editor. To run the examples, build the NetDocEnum assembly as described in Building a .NET Application for MATLAB Examples.

If the NetDocEnum assembly is in your c:\work folder, load the file:

dllPath = fullfile('c:','work','NetDocEnum.dll');
asm = NET.addAssembly(dllPath);
asm.Enums
ans = 
    'NetDocEnum.MyDays'
    'NetDocEnum.Range'

Refer to a .NET Enumeration Member

You use an enumeration member in your code as an instance of an enumeration. To refer to an enumeration member, use the C# namespace, enumeration, and member names:

Namespace.EnumName.MemberName

For example, the System namespace in the .NET Framework class library has a DayOfWeek enumeration. The members of this enumeration are:

Enumeration members for class 'System.DayOfWeek':
    Sunday
    Monday
    Tuesday
    Wednesday
    Thursday
    Friday
    Saturday

To create a variable with the value Thursday, type:

gameDay = System.DayOfWeek.Thursday;
whos
  Name     Size Bytes Class

  gameDay  1x1  104   System.DayOfWeek

Using the Implicit Constructor.  The implicit constructor, Namespace.EnumName, creates a member with the default value of the underlying type. For example, the NetDocEnum.Range enumeration has the following members:

Enumeration members for class 'NetDocEnum.Range':
    Max
    Min

Type:

x = NetDocEnum.Range
whos x
x = 
0

  Name  Size  Bytes  Class

  x     1x1   104    NetDocEnum.Range

Work with Members of a .NET Enumeration

To display the member names of an enumeration, use the MATLAB enumeration function. For example, to list the member names of the System.DayOfWeek enumeration, type:

enumeration('System.DayOfWeek')
Enumeration members for class 'System.DayOfWeek':
    Sunday
    Monday
    Tuesday
    Wednesday
    Thursday
    Friday
    Saturday

You cannot use the enumeration command to return arrays of .NET enumeration objects. You can read the names and values of the enumeration into arrays, using the System.Enum methods GetNames, GetValues, and GetType. For more information about using these methods, see Information About System.Enum Methods.

For example, to create arrays allNames and allValues for the System.DayOfWeek enumeration, type:

myDay = System.DayOfWeek;
allNames = System.Enum.GetNames(myDay.GetType);
allValues = System.Enum.GetValues(myDay.GetType);

The class of the names array is System.String, while the class of the values array is the enumeration type System.DayOfWeek.

whos all*
  Name       Size  Bytes  Class

  allNames   1x1   112    System.String[]
  allValues  1x1   112    System.DayOfWeek[]

Although the types are different, the information MATLAB displays is the same. For example, type:

allNames(1)
ans = 
Sunday

Type:

allValues(1)
ans = 
Sunday

For an example that uses arrays, see Iterate Through a .NET Enumeration. For information about using System.String, see How MATLAB Handles System.String.

Default Methods for an Enumeration

By default, MATLAB provides the following methods for a .NET enumeration:

For example, type:

methods('System.DayOfWeek')
Methods for class System.DayOfWeek:

CompareTo    eq
DayOfWeek    ge
Equals       gt
GetHashCode  int32
GetType      le
GetTypeCode  lt
ToString     ne
char
double

The method to get the underlying value is int32.

For examples using these methods, see Example Using Relational Operations, Example Using Switch Statements, and Display .NET Enumeration Members as Character Strings.

The NetDocEnum.MyDays enumeration, which has the Flags attribute, has the bit-wise methods. To list the methods, type:

methods('NetDocEnum.MyDays')
Methods for class NetDocEnum.MyDays:

CompareTo    char         
Equals       double       
GetHashCode  eq           
GetType      ge           
GetTypeCode  gt           
MyDays       int32        
ToString     le           
bitand       lt           
bitnot       ne           
bitor        
bitxor

For more information about bit-wise operators, see Use Bit Flags with .NET Enumerations.

Display .NET Enumeration Members as Character Strings

Use the char method to get the descriptive name of an enumeration. For example, type:

gameDay = System.DayOfWeek.Thursday;
['Next volleyball game is ',char(gameDay)]
ans =
Next volleyball game is Thursday

Convert .NET Enumeration Values to Type Double

To convert a value to a MATLAB double, type:

gameDay = System.DayOfWeek.Thursday;
myValue = double(gameDay)
myValue =
     4

Underlying Values

MATLAB supports enumerations of any numeric type.

To find the underlying type of an enumeration, use the System.Enum static method GetUnderlyingType. For example, the following C# statement in the NetDocEnum assembly declares the enumeration Range:

public enum Range : long {Max = 2147483648L,Min = 255L}

To display the underlying type:

maxValue = NetDocEnum.Range.Max;
System.Enum.GetUnderlyingType(maxValue.GetType).FullName
ans = 
System.Int64

Iterate Through a .NET Enumeration

To display all member names of the System.DayOfWeek enumeration, create a System.String array of names. Use the Length property of this array to find the number of members. For example:

myDay = System.DayOfWeek;
allNames = System.Enum.GetNames(myDay.GetType);
disp(['Members of ' class(myDay)]);
for idx = 1:allNames.Length
    disp(allNames(idx));
end
Members of System.DayOfWeek
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday

Information About System.Enum Methods

To create MATLAB arrays from an enumeration, use the static System.Enum methods GetNames and GetValues. The input argument for these methods is an enumeration type. Use the GetType method for the type of the current instance. To display the signatures for these methods, type:

methodsview('System.Enum')

Look at the following signatures:

QualifiersReturn TypeNameArguments
 System.TypeGetType(System.Enum this)
StaticSystem.String[]GetNames(System.Type enumType)
StaticSystem.ArrayGetValues(System.Type enumType)

To use GetType, create an instance of the enumeration. For example:

myEnum = System.DayOfWeek;

The enumType for myEnum is:

myEnumType = myEnum.GetType;

To create an array of names using the GetNames method, type:

allNames = System.Enum.GetNames(myEnumType);

Alternatively:

allNames = System.Enum.GetNames(myEnum.GetType);

Use .NET Enumerations to Test for Conditions

With relational operators, you can use enumeration members in if and switch statements and other functions that test for equality.

Example Using Switch Statements

The following Reminder function displays a message depending on the day of the week:

function Reminder(day)
% day = System.DayOfWeek enumeration value
% Add error checking here
switch(day)
    case System.DayOfWeek.Monday
        disp('Department meeting at 10:00');
    case System.DayOfWeek.Tuesday
        disp('Meeting Free Day!');
    case {System.DayOfWeek.Wednesday System.DayOfWeek.Friday}
        disp('Team meeting at 2:00');
    case System.DayOfWeek.Thursday
        disp('Volley ball night');
end
end

For example, type:

today = System.DayOfWeek.Wednesday;
Reminder(today)
ans =
Team meeting at 2:00

Example Using Relational Operations

Create the following function to display a message:

function VolleyballMessage(day)
% day = System.DayOfWeek enumeration value
if gt(day,System.DayOfWeek.Thursday)
    disp('See you next week at volleyball.')
else
    disp('See you Thursday!')
end
end

For a day before Thursday:

myDay = System.DayOfWeek.Monday;
VolleyballMessage(myDay)
See you Thursday!

For a day after Thursday:

myDay = System.DayOfWeek.Friday;
VolleyballMessage(myDay)
See you next week at volleyball.

Example — Read Special System Folder Path

function result = getSpecialFolder(arg)
% Returns the special system folders such as "Desktop", "MyMusic" etc.
% arg can be any one of the enum element mentioned in this link
% http://msdn.microsoft.com/en-us/library/system.environment.specialfolder.aspx
% e.g. 
%       >> getSpecialFolder('Desktop')
%
%       ans = 
%       C:\Users\jsmith\Desktop
 
%get the type of SpecialFolder enum, this is a nested enum type.
specialFolderType = System.Type.GetType(...
    'System.Environment+SpecialFolder');
%Get a list of all SpecialFolder enum values 
folders = System.Enum.GetValues(specialFolderType);
enumArg = [];
 
%Find the matching enum value requested by the user
for i=1:folders.Length
    if (strcmp(char(folders(i)), arg))
        enumArg = folders(i);
    break;
    end
end
 
%Validate
if(isempty(enumArg))
    error('Invalid Argument');
end
 
%Call GetFolderPath method and return the result
result = System.Environment.GetFolderPath(enumArg);
end

Use Bit Flags with .NET Enumerations

Many .NET languages support bit-wise operations on enumerations defined with the System.Flags attribute. The MATLAB language does not have equivalent operations, and, therefore, provides instance methods for performing bit-wise operations on an enumeration object. The bit-wise methods are bitand, bitnot, bitor, and bitxor.

An enumeration can define a bit flag. A bit flag lets you create instances of an enumeration to store combinations of values defined by the members. For example, files and folders have attributes, such as Archive, Hidden and ReadOnly. For a given file, perform an operation based on one or more of these attributes. With bit-wise operators, you can create and test for combinations.

To use bit-wise operators, the enumeration must have:

Use the NetDocEnum.MyDays enumeration in the following examples. For more information, see Using the NetDocEnum Example Assembly.

Creating Enumeration Bit Flags

Suppose you have the following scheduled activities:

You can combine members of the MyDays enumeration to create MATLAB variables using the bitor method, which joins two members. For example, to create a variable teamMtgs of team meeting days, type:

teamMtgs = bitor(...
    NetDocEnum.MyDays.Friday,...
    NetDocEnum.MyDays.Wednesday);

Create a variable allMtgs of all days with meetings:

allMtgs = bitor(teamMtgs,...
    NetDocEnum.MyDays.Monday);

To see which days belong to each variable, type:

teamMtgs
allMtgs
teamMtgs = 
Wednesday, Friday

allMtgs = 
Monday, Wednesday, Friday

Removing a Flag from a Variable

Suppose your manager cancels the Wednesday meeting this week. Use the bitxor method to remove Wednesday from the allMtgs variable.

thisWeekMtgs = bitxor(allMtgs,NetDocEnum.MyDays.Wednesday)
thisWeekMtgs = 
Monday, Friday

Using a bit-wise method such as bitxor on allMtgs does not modify the value of allMtgs. This example creates a new variable, thisWeekMtgs, which contains the result of the operation.

Replacing a Flag in a Variable

Suppose you change the team meeting permanently from Wednesday to Thursday. Use bitxor to remove Wednesday, and use bitor to add Thursday. Since this is a permanent change, update the teamMtgs and allMtgs variables.

teamMtgs = bitor(...
    (bitand(teamMtgs,...
        bitnot(NetDocEnum.MyDays.Wednesday))),...
    NetDocEnum.MyDays.Thursday);
allMtgs = bitor(teamMtgs,...
    NetDocEnum.MyDays.Monday);
teamMtgs
allMtgs
teamMtgs = 
Thursday, Friday

allMtgs = 
Monday, Thursday, Friday

Testing for Membership

Create the following RemindMe function:

function RemindMe(day)
% day = NetDocEnum.MyDays enumeration
teamMtgs = bitor(...
    NetDocEnum.MyDays.Friday,...
    NetDocEnum.MyDays.Wednesday);
allMtgs = bitor(teamMtgs,...
    NetDocEnum.MyDays.Monday);

if eq(day,bitand(day,teamMtgs))
    disp('Team meeting today.')
elseif eq(day,bitand(day,allMtgs))
    disp('Meeting today.')    
else
    disp('No meetings today!')
end
end

Use the RemindMe function:

today = NetDocEnum.MyDays.Monday;
RemindMe(today)
Meeting today.

Limitations to Support of .NET Enumerations

You cannot create arrays of .NET enumerations, or any .NET objects, in MATLAB.

  


Recommended Products

Includes the most popular MATLAB recorded presentations with Q&A sessions led by MATLAB experts.

 © 1984-2012- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS