including enums in classes
While i find the concept of enums quite handy from my C days, I wanted to figure out how to include them in C# classes, but it wasn't immediately obvious. Declaring an enum is simple enough:
enum MaritalStatus
{
Single=0,
Married=1,
Divorced =2,
Widowed=3
}
When actually including it in an object, though, you need to include it as a member attribute in the class. It's probably wise to use a slightly different naming convention than in the original enum to prevent ambiguity for your friendly compiler. Include it initially as an attribute, just as if you were using any other type:
namespace App
{
class Person
{
//attributes
private string name;
private string address;
private MaritalStatus mstat;
...
}
}
as a property, remember to use the naming convetion used in the class definition, not the full name.
public MaritalStatus Mstat
{
set
{
this.mstat = value;
}
get
{
return (this.mstat);
}
}
Including it in a member function is also quite straightforward:
public void PrintDetails()
{
Console.WriteLine("{0} is {1} and lives at {2}.\n", this.Name, this.mstat.ToString(), this.Address);
}
In this case the .ToString() method converts the enum from its integer value, to the textual value that you have defined for the enum. The above member would output the following:
Peter is Married and lives at 106 Bonsall Road.
The this.mstat.ToString() function puts the string equivalent value of the enum in the place of the integer itself. If you wanted to retreive the underlying integer, you should re-cast the value to its underlying type.
Console.WriteLine((int)mstat); // writes out '1' instead of the value Married.
- Login or register to post comments
- Email this Story