Using Structs in C#

Structs are the userdefined data type. Structs are defined by using the struct keyword in c#.

for example:
public struct StructA
{
public int x, y;

public A(int p1, int p2)
{
x = p1;
y = p2;
}
}


It is an error to define a default (parameterless) constructor for a struct. It is also an error to initialize an instance field in a struct body. You can initialize struct members only by using a parameterized constructor or by accessing the members individually after the struct is declared.

This example demonstrates struct initialization using both default and parameterized constructors.

public struct StructA
{
public int x, y;

public StructA (int p1, int p2)
{
x = p1;
y = p2;
}
}

class TestStructA
{
static void Main()
{
// Initialize:
StructA StructA1 = new StructA();
StructA StructA2 = new StructA(10, 10);

// Display results:
Console.Write("StructA 1: ");
Console.WriteLine("x = {0}, y = {1}", StructA1.x, StructA1.y);

Console.Write("StructA 2: ");
Console.WriteLine("x = {0}, y = {1}", StructA2.x, StructA2.y);

// Keep the console window open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}

Structs Almost have same syntax as classes, But structs are more limited than classes:

• Within a struct declaration, fields cannot be initialized unless they are declared as const or static.

• A struct cannot declare a default constructor (a constructor without parameters) or a destructor.

• Structs are copied on assignment. When a struct is assigned to a new variable, all the data is copied, and any modification to the new copy does not change the data for the original copy.

• Structs are value types but classes are reference types.

• structs can be instantiated without using a new operator.

• Structs can declare constructors that have parameters.

• A struct cannot support the inheritance.

• All structs inherit directly from System.ValueType, which inherits from System.Object.

• A struct can implement interfaces.

• A struct can be used as a nullable type and can be assigned a null value.
Tags: , ,

Join Us!