Login

Username:

Password: 

Join us Now |  Forgot Password? | Forgot UserName?

C#

Learn step by step



Struct

A structure in C# is simply a composite data type consisting of a number elements of other types. 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.

Structure Declaration & Object Creation

The keyword struct can be used to declare a structure. The general form of a structure declaration in C# is as follows.

<modifiers> struct <struct_name>
{
//Structure members
}
Structs & Fields

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
}


using System;
struct MyStruct
{
public int x;
public int y;
}
class MyClient
{
public static void Main()
{
MyStruct ms = new MyStruct();
ms.x = 10;
ms.y = 20;
int sum = ms.x + ms.y;
Console.WriteLine("The sum is {0}",sum);
}
}

Output

30

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.
Remember that static fields can't be accessed by an instance of a struct. We can access them only by using the struct names.

Struct & Methods

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.


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();
}
}


Related Videos