C# Struct and Enumeration
Struct
Structs are similar to classes except they are value types designed to implement lean and mean data types. Also, structs don't support inheritance, parameterless constructors, or destructors. Structs do support methods and properties, and they can implement interfaces, static and instance members, and static and instance constructors.
Because structs are value types, they’re allocated on the stack and are allocated and deallocated efficiently without requiring garbage collection. If the struct is too large, however, passing it as a value parameter can become inefficient compared to a class that simply passes the value of the reference. Therefore, developers should keep structs relatively small.
The following example shows a simple struct declaration.
using System;
struct Employee
{
int intEmpID;
public Employee(int value)
{
intEmpID= value;
}
public void Print()
{
Console.WriteLine("Employee is {0}", intEmpID);
}
}
class TestEmployee
{
public static void Main()
{
Employee objEmp= new Employee (1);
objEmp.Print();
}
}
Enumerations
Enumerations define a set of values for data. Enumerations are considered value types and, therefore, instances are allocated on the stack. The base type of an enumerator may be one of byte, sbyte, short, ushort, int, uint, long, or ulong. The default base type is int.
The following sample illustrates the declaration and use of enumerators:
using System;
class Enums
{
enum Directions
{
North,
South,
East,
West
}
public static void Main()
{
Directions dir= Directions.North;
Console.WriteLine("Direction is {0}", dir);
}
}
This sample produces the following results:
Direction is North
In addition, enumeration members can specify values explicitly in their declaration and multiple members may share the same value.
enum Directions
{
North=1,
South,
East,
West
Bangalore=South
}
When no value is explicitly assigned, the first enumeration member has a value of 0 and each of the other member’s value is the value of the previous member plus one. Enumerations are based on the System.Enum type.
No comments:
Post a Comment