Click here to Skip to main content
Click here to Skip to main content
Go to top

Enums and Structs in C#

, 13 Oct 2001
Rate this:
Please Sign up or sign in to vote.
Two oft-overlooked value types that C# offers and where they can be used

Introduction

Just about everything is a heap object when you are using C#. Only elementary native types like int are treated as value types. But there are two value types in C# that are pretty much more useful that first glances would tell you. They are the enum and struct types. Very few tutorials even cover these topics, but they have their own uses. And both of them are a lot more efficient than classes and you can use them in place of classes when they meet your requirements to improve performance.

Enums

Enums are basically a set of named constants. They are declared in C# using the enum keyword. Every enum type automatically derives from System.Enum and thus we can use System.Enum methods on our Enums. Enums are value types and are created on the stack and not on the heap. You don't have to use new to create an enum type. Declaring an enum is a little like setting the members of an array as shown below.

enum Rating {Poor, Average, Okay, Good, Excellent}

You can pass enums to member functions just as if they were normal objects. And you can perform arithmetic on enums too. For example we can write two functions, one to increment our  enum and the other to decrement our enum.

Rating IncrementRating(Rating r)
{
    if(r == Rating.Excellent)
        return r;
    else
        return r+1;
}
Rating DecrementRating(Rating r)
{
    if(r == Rating.Poor)
        return r;
    else
        return r-1;
}

Both functions take a Rating object as argument and return back a Rating object. Now we can simply call these functions from elsewhere.

for (Rating r1 = Rating.Poor; 
    r1 < Rating.Excellent ; 
    r1 = IncrementRating(r1))
{           
    Console.WriteLine(r1);
}

Console.WriteLine();

for (Rating r2 = Rating.Excellent; 
    r2 > Rating.Poor; 
    r2 = DecrementRating(r2))
{
    Console.WriteLine(r2);          
}

And here is a sample code snippet showing how you can call System.Enum methods on our Enum object. We call the GetNames method which retrieves an array of the names of the constants in the enumeration.

foreach(string s in Rating.GetNames(typeof(Rating)))
    Console.WriteLine(s);

Where to use enums

Quite often we have situations where a class method takes as an argument a custom option. Let's say we have some kind of file access class and there is a file open method that has a parameter that might be one of read-mode, write-mode, read-write-mode, create-mode and append-mode. Now you might think of adding five static member fields to your class for these modes. Wrong approach! Declare and use an enumeration which is a whole lot more efficient and is better programming practice in my opinion.

Structs

In C++ a struct is just about the same as a class for all purposes except in the default access modifier for methods. In C# a struct are a pale puny version of a class. I am not sure why this was done so, but perhaps they decided to have a clear distinction between structs and classes. Here are some of the drastic areas where classes and structs differ in functionality.

  • structs are stack objects and however much you try you cannot create them on the heap
  • structs cannot inherit from other structs though they can derive from interfaces
  • You cannot declare a default constructor for a struct, your constructors must have parameters
  • The constructor is called only if you create your struct using new, if you simply declare the struct just as in  declaring a native type like int, you must explicitly set each member's value before you can use the struct
struct Student : IGrade
{   
    public int maths;
    public int english;
    public int csharp;

    //public member function
    public int GetTot()
    {
        return maths+english+csharp;
    }

    //We have a constructor that takes an int as argument
    public Student(int y)
    {
        maths = english = csharp = y;
    }

    //This method is implemented because we derive
    //from the IGrade interface
    public string GetGrade()
    {
        if(GetTot() > 240 )
            return "Brilliant";
        if(GetTot() > 140 )
            return "Passed";
        return "Failed";
    }
}

interface IGrade
{
    string GetGrade();
}

Well, now let's take a look at how we can use our struct.

Student s1 = new Student();
Console.WriteLine(s1.GetTot());
Console.WriteLine(s1.GetGrade());

//Output
0
Failed

Here the default constructor gets called. This is automatically implemented for us and we cannot have our own default parameter-less constructor. The default parameter-less constructor simply initializes all values to their zero-equivalents. This is why we get a 0 as the total.

Student s2;
s2.maths = s2.english = s2.csharp = 50;
Console.WriteLine(s2.GetTot());
Console.WriteLine(s2.GetGrade());

//Output
150
Passed

Because we haven't used new, the constructor does not get called. Of all the silly features this one must win the annual contest by a long way. I see no sane reason why this must be so. Anyway you have to initialize all the member fields. If you comment out the line that does the initialization you will get a compiler error :- Use of unassigned local variable 's2'

Student s3 = new Student(90);
Console.WriteLine(s3.GetTot());
Console.WriteLine(s3.GetGrade());

//Output
270
Brilliant

This time we use our custom constructor that takes an int as argument.

When to use structs

Because structs are value types they would be easier to handle and more efficient that classes. When you find that you are using a class mostly for storing a set of values, you must replace those classes with structs. When you declare arrays of structs because they are created on the heap, efficiency again improves. Because if they were classes each class object would need to have memory allocated on the heap and their references would be stored. In fact lots of classes within the .NET framework are actually structs. For example System.Drawing.Point is actually a struct and not a class.

License

This article, along with any associated source code and files, is licensed under The Common Public License Version 1.0 (CPL)

Share

About the Author

Nish Sivakumar

United States United States
Nish is a real nice guy who has been writing code since 1990 when he first got his hands on an 8088 with 640 KB RAM. Originally from sunny Trivandrum in India, he has been living in various places over the past few years and often thinks it’s time he settled down somewhere.
 
Nish has been a Microsoft Visual C++ MVP since October, 2002 - awfully nice of Microsoft, he thinks. He maintains an MVP tips and tricks web site - www.voidnish.com where you can find a consolidated list of his articles, writings and ideas on VC++, MFC, .NET and C++/CLI. Oh, and you might want to check out his blog on C++/CLI, MFC, .NET and a lot of other stuff - blog.voidnish.com.
 
Nish loves reading Science Fiction, P G Wodehouse and Agatha Christie, and also fancies himself to be a decent writer of sorts. He has authored a romantic comedy Summer Love and Some more Cricket as well as a programming book – Extending MFC applications with the .NET Framework.
 
Nish's latest book C++/CLI in Action published by Manning Publications is now available for purchase. You can read more about the book on his blog.
 
Despite his wife's attempts to get him into cooking, his best effort so far has been a badly done omelette. Some day, he hopes to be a good cook, and to cook a tasty dinner for his wife.

Comments and Discussions

 
GeneralMy vote of 5 PinmemberSChristmas1-Aug-12 3:52 
SuggestionUnions PinmemberVuNic11-Jun-12 21:58 
AnswerRe: Unions PinmvpNish Sivakumar12-Jun-12 3:32 
QuestionImport WIN32 DLL Pinmemberkurniawan Indra25-Jul-11 20:31 
GeneralMy vote of 5 PinmemberSAKryukov17-Feb-11 12:21 
GeneralRe: My vote of 5 PinmvpNishant Sivakumar17-Feb-11 13:13 
QuestionProblem of Event and Delegate Pinmembersanjayror25-Oct-08 8:00 
GeneralNewbie Question Pinmemberakobold31-Jan-07 2:15 
AnswerRe: Newbie Question PinmemberKevinyou26-May-07 5:45 
QuestionHow to load a lot of data into structs? PinmemberBrent_Daignault14-Oct-05 11:11 
GeneralProblems with structs in C# Pinmemberghost12077-Feb-05 0:11 
GeneralRe: Problems with structs in C# PinsussAnonymous9-Mar-05 6:49 
GeneralRe: Problems with structs in C# Pinmemberkam1814-Aug-06 9:28 
GeneralUsing typedef structs in C# ,C++ Pinmemberarssa202017-Jun-04 9:26 
QuestionDoes know anybody how to extend a enum? Pinmembersrlopez25-Feb-03 4:21 
AnswerRe: Does know anybody how to extend a enum? PinmemberDaniel Turini25-Feb-03 4:32 
GeneralRe: Does know anybody how to extend a enum? Pinmembersrlopez25-Feb-03 4:40 
GeneralRe: Does know anybody how to extend a enum? PinmemberDaniel Turini25-Feb-03 4:42 
GeneralRe: Does know anybody how to extend a enum? Pinmemberdoohickeywannabeewannabe26-Nov-06 11:58 
AnswerRe: Does know anybody how to extend a enum? PinmemberKevinyou26-May-07 6:23 
QuestionLanguage bug or language feature? Pinmemberdcbrower8-Jan-03 4:26 
GeneralGuess: why no overloading default struct ctor Pinmemberwilltsmith4-Jan-03 20:08 
GeneralYou rock Nish PinsitebuilderPaul Watson4-Nov-02 7:57 
GeneralRe: You rock Nish PineditorNishant S4-Nov-02 14:18 
GeneralRe: You rock Nish PinsitebuilderPaul Watson5-Nov-02 19:13 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.140926.1 | Last Updated 14 Oct 2001
Article Copyright 2001 by Nish Sivakumar
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid