Enumerations and structures in C#

✓ Enumerations – Enumerations are value type.

// declaring an enumeration
enum Season { Spring, Summer, Fall, Winter }

//using enumeration
Season colorful = Season.Fall;
Console.WriteLine(colorful); // writes out 'Fall'

string name = colorful.ToString();
Console.WriteLine(name); // also writes out 'Fall'

Console.WriteLine((int)colorful); // Casting. Writes out '2'

//A specific integer constant can also associate with an enumeration literal
enum Season { Spring = 1, Summer, Fall, Winter }

// Enum can also created with different data type
enum Season : short { Spring, Summer, Fall, Winter }

enum Month
{
    January, February, March, April, May, June, July, August, September,
    October, November, December
}
Month first = Month.January;
Console.WriteLine(first); // January
first++;
Console.WriteLine(first); // February

✓ Structures – A structure is a value type, and its instances are live on the stack. On the otherhand class instances are called objects and live on the heap.

In C#, the primitive numeric types int, long, and float are aliases for the structures System.Int32, System.Int64, and System.Single.

Operators, such as the equality operator (==) and the in-equality operator (!=) can’t be used with structure type variables. However, you can use the built-in Equals() method exposed by all structures to compare them.

struct Time
{
private int hours, minutes, seconds;
public Time(int hh, int mm)
{
hours = hh;
minutes = mm;
seconds = 0;
}
}

Time now = new Time(12, 30);
Time copy = now;

When you copy a structure variable, each field on the left side is set directly from the corresponding field on the right side.


struct Time
{
    private int hours, minutes, seconds;
    public Time(int hh, int mm)
    {
        hours = hh;
        minutes = mm;
        seconds = 0;
    }
}

Time now = new Time(12, 30);
Time copy = now;
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s