Whats the difference betweeen Structure, Class and Enumeration

Posted by Sandip Monday, November 16, 2009

Structures and Enumerations are Value-Types. This means, the data that they contain is stored as a stack on the memory. Classes are Reference-Types, means they are stored as a heap on the memory.
Structures are implicitly derived from a class called System.ValueType. The purpose of System.ValueType is to override the virtual methods defined by System.Object. So when the runtime encounters a type derived from System.ValueType, then stack allocation is achieved. When we allocate a structure type, we may also use the new keyword. We may even make a constructor of a structure, but, remember, A No-argument constructor for a structure is not possible. The structure's constructor should always have a parameter.

So if we define the following structure

struct MyStruct
{
public int y,z;
}
and we create a structure type
MyStruct st = new MyStruct();

In case of a class, no-argument constructors are possible. Class is defined using the class keyword.

A struct cannot have an instance field, whereas a class can.

class A
{
int x = 5; //No error
...
}

struct
{
int x = 5; //Syntax Error
}

A class can inherit from one class (Multiple inheritance not possible). A Structure cannot inherit from a structure.

Enum is the keyword used to define an enumeration. An enumeration is a distinct type consisting of a set of named constants called the enumerator list. Every enumeration has an underlying type. The default type is "int". Note: char cant be the underlying data type for enum. First value in enum has value 0, each consequent item is increased by 1.

enum colors {red, green, blue, yellow};

Here, red is 0, green is 1, blue is 2 and so on.
An explicit casting is required to convert an enum value to its underlying type

int x = (int)colors.yellow;

0 comments

Post a Comment