A Structure in C#
A Structure in C#
A C#
structure is a value type and the instances or objects of a structure are created in stack. The structure in C# can
contain fields, methods, constants, constructors, properties, indexers, operators and even other structure types.
The keyword struct can be used to declare a structure. The general form of a structure declaration in C# is as
follows.
Where the modifier can be private, public, internal or public. The struct is the required keyword.
For example
struct MyStruct
{
public int x;
public int y;
}
The objects of a strcut can be created by using the new operator as follows.
The individual members of a struct can be accessed by using the dot (.) operator as showing below.
ms.x = 10;
ms.y = 20;
Remember that unlike classes, the strcut object can also be created without using the new operator.
MyStruct ms;
But in this case all fields of the struct will remain unassigned and the object can't be used until all of the fields
are initialized.
A struct in C# can contain fields. These fields can be declared as private, public, internal. Remember that inside
a struct, we can only declare a field. We can't initialize a field inside a struct. However we can use constructor to
initialize the structure fields.
The following is not a valid C# struct and the code will not compile, since the fields inside the structure are
trying to initialize.
struct MyStruct
{
int x = 20; // Error its not possible to initialize
int y = 20; // Error its not possible to initialize
}
However a struct can contain static fields, which can be initialized inside the struct. The following example
shows the use of static fields inside a struct.
// Author: [email protected]
using System;
struct MyStruct
{
public static int x = 25;
public static int y = 50;
}
class MyClient
{
public static void Main()
{
int sum = MyStruct.x + MyStruct.y;
Console.WriteLine("The sum is {0}",sum);
}
}
Remember that static fields can't be accessed by an instance of a struct. We can access them only by using the
struct names.
A C# struct can also contain methods. The methods can be either static or non-static. But static methods can
access only other static members and they can't invoke by using an object of the structure. They can invoke only
by using the struct name.
// Author: [email protected]
using System;
struct MyStruct
{
static int x = 25;
static int y = 50;
public void SetXY(int i, int j)
{
x = i;
y = j;
}
public static void ShowSum()
{
int sum = x + y;
Console.WriteLine("The sum is {0}",sum);
}
}
class MyClient
{
public static void Main()
{
MyStruct ms = new MyStruct();
ms.SetXY(100,200);
MyStruct.ShowSum();
}
}
The methods inside a struct can also be overloaded as like inside a class. For example
// Author:[email protected]
using System;
struct MyStruct
{
static int x = 25;
static int y = 50;
public void SetXY(int i, int j)
{
x = i;
y = j;
}
public void SetXY(int i)
{
x = i;
y = i;
}
}
class MyClient
{
public static void Main()
{
MyStruct ms1 = new MyStruct();
MyStruct ms2 = new MyStruct();
ms1.SetXY(100,200);
ms2.SetXY(500);
}
}
A C# struct can declare constrcutor, but they must take parameters. A default constructor (constructor without
any parameters) are always provided to initialize the struct fields to their default values. The parameterized
constructors inside a struct can also be overloaded.
// Author: [email protected]
using System;
struct MyStruct
{
int x ;
int y ;
{ x = i; y = j;}
public MyStruct(int i)
{ x = y = i; }
public void ShowXY()
{ Console.WriteLine("The field values are {0} & {1}",x,y); }
}
class MyClient
{
public static void Main()
{
MyStruct ms1 = new MyStruct(10,20);
MyStruct ms2 = new MyStruct(30);
ms1.ShowXY();
ms2.ShowXY();
}
}
The 'this' operator can also be used in constructors and parameterized constructors can be chained inside a C#
constructor. An example is given below.
// Author: [email protected]
using System;
struct MyStruct
{
int x ;
int y ;
public MyStruct(int i, int j):this(i+j)
{}
public MyStruct(int i)
{ x = y = i; }
public void ShowXY()
{ Console.WriteLine("The field values are {0} & {1}",x,y); }
}
class MyClient
{
public static void Main()
{
MyStruct ms1 = new MyStruct(10,20);
ms1.ShowXY();
}
}
//C#: Property
// Author: [email protected]
using System;
class MyStruct
private int x;
public int X
{
get
{
return x;
}
set
{
x = value;
}
}
}
class MyClient
public static void Main()
{
MyStruct ms = new MyStruct();
ms.X = 10;
int xVal = ms.X;
Console.WriteLine(xVal);//Displays 10
}
}
The indexers can also be used with a C# struct. An example is shown below.
// Author: [email protected]
using System;
using System.Collections;
struct MyStruct
{
public string []data ;
public string this [int index]
{
get
{
return data[index];
}
set
{
data[index] = value;
}
}
}
class MyClient
{
public static void Main()
{
MyStruct ms = new MyStruct();
ms.data = new string[5];
ms[0] = "Rajesh";
ms[1] = "A3-126";
ms[2] = "Snehadara";
ms[3] = "Irla";
ms[4] = "Mumbai";
Console.WriteLine("{0},{1},{2},{3},{4}",ms[0],ms[1],ms[2],ms[3],ms[4]);
}
}
The operators can be overloaded inside a C# structure also. The same rules applicable with respect to a C# class
are also applicable here. Both unary and binary operators can be overloaded.
// Author: [email protected]
using System;
struct Complex
{
private int x;
private int y;
public Complex(int i, int j)
{
x = i;
y = j;
}
public void ShowXY()
{
Console.WriteLine("{0} {1}",x,y);
}
public static Complex operator -(Complex c)
{
Complex temp = new Complex();
temp.x = -c.x;
temp.y = -c.y;
return temp;
}
}
class MyClient
{
public static void Main()
{
Complex c1 = new Complex(10,20);
c1.ShowXY(); // displays 10 & 20
Complex c2 = new Complex();
c2.ShowXY(); // displays 0 & 0
c2 = -c1;
c2.ShowXY(); // diapls -10 & -20
}
}
There is no inheritance for structs as there is for classes. A struct can't inherit from another struct or class and it
can't be the base class for a class. But remember that in C# all types are directly or indirectly inheriting from the
super base class object and hence the structure also. Since structs doesn't support inheritance, we can't use the
keywords virtual, override, new, abstract etc with a struct methods. C# struct types are never abstract and are
always implicitly sealed. The abstract or sealed modifiers are not permitted in a struct declaration.
Since inheritance is not supported for structs, the declared accessibility of a struct member can't be protected or
protected internal. Since all struct types are implicitly inherit from object class, it is possible to override the
methods of the object class inside a struct by using the keyword override. Remember that this is special case in
C# structs.
Just like classes, a C# struct can also implement from an interface. For example
// Author:[email protected]
using System;
interface IInterface
{
void Method();
}
struct Complex : IInterface
{
public void Method()
{
Console.WriteLine("Struct Method");
}
}
class MyClient
{
public static void Main()
{
Complex c1 = new Complex();
c1.Method();
}
}
The structs in C# seems to similar to classes. But they are two entirely different aspects of the language. The
classes are reference types while a struct is a value type in C#. The objects of class types are always created on
heal while the objects of struct types are always created on the stack. But C# structs are useful for small data
structures that have value semantics. Complex numbers, points in a co-ordinate systems etc are good examples
for struct types.
The enum keyword is used to declare an enumeration, a distinct type that consists of a set of named constants
called the enumerator list.
Usually it is best to define an enum directly within a namespace so that all classes in the namespace can
access it with equal convenience. However, an enum can also be nested within a class or struct.
By default, the first enumerator has the value 0, and the value of each successive enumerator is increased by
1. For example, in the following enumeration, Sat is 0, Sun is 1, Mon is 2, and so forth.
enum Days {Sat, Sun, Mon, Tue, Wed, Thu, Fri};
Enumerators can use initializers to override the default values, as shown in the following example.
enum Days {Sat=1, Sun, Mon, Tue, Wed, Thu, Fri};
In this enumeration, the sequence of elements is forced to start from 1 instead of 0. However, including a
constant that has the value of 0 is recommended. For more information, see Enumeration Types.
Every enumeration type has an underlying type, which can be any integral type except char. The default
underlying type of enumeration elements is int. To declare an enum of another integral type, such as byte, use
a colon after the identifier followed by the type, as shown in the following example.
enum Days : byte {Sat=1, Sun, Mon, Tue, Wed, Thu, Fri};
A variable of type Days can be assigned any value in the range of the underlying type; the values are not
limited to the named constants.
an explicit cast is necessary to convert from enum type to an integral type. For example, the following
statement assigns the enumerator Sun to a variable of the type int by using a cast to convert
from enumto int.
int x = (int)Days.Sun;
public class EnumTest
{
enum Days { Sun, Mon, Tue, Wed, Thu, Fri, Sat };