Structures in C# are similar to classes but are value types stored on the stack. The document defines a Student struct with roll_number and Name properties, and shows how to declare a variable of the struct type, assign values to its properties, and copy one struct to another. Structs can also contain methods, as shown in the Rectangle struct example which defines a constructor, Area method, and Display method. Nested structs are also possible, like an Employee struct containing a nested Salary struct. The key differences between structs and classes are that structs are value types stored on the stack while classes are reference types.
Structures in C#
Structure are similar to classes in C#.
They are value type and stored on the stack.
Defining a Struct
struct struct-name
{
data member-1;
data member-2;
}
Example
Struct student
{
public int roll_no;
public string Name;
}
Dr Neeraj Kumar Pandey
student s1;//Declare a
student
3.
Assigning Values toMembers
Members variables can be accessed using the simple dot
notation as follows:-
s1.Name=“Raju”;
s1.roll_numer=“89”;
We may also use the member variables in expressions on
the right-hand side:-
y=x1.z+60;
Dr Neeraj Kumar Pandey
4.
Copying Struct
Dr NeerajKumar Pandey
We can also copy values from one struct to another .
student s2;//s2 is declared
s2=s1;
This will copy all those values from s1 to s2.
We can also use the operator new to create struct variables
student s3= new student();
A struct variable is initialized to the default values of its members as
soon as it declared.
Struct data members are private by default.
5.
Structs with Methods
We can assign values to the data members using constructors.
struct Number
{
int number;
public Number(int value)
{
number= value;
}
}
The constructor will be invoked as:-
Number n1= new Number(100);
C# doesn’t support default constructors.
structs can also have other methods as members.
structs are not permitted to declare destructors.
Dr Neeraj Kumar Pandey
6.
Struct with Methods(contd)
usingSystem;
struct Rectangle
{
int a,b;
public Rectangle(int x, int y)
{
a=x;
b=y;
}
public int Area()
{
return (a*b);
}
Dr Neeraj Kumar Pandey
public void Display()
{
Console.WriteLine("Area="+
Area());
}
}
class TestRectangle
{
public static void Main()
{
Rectangle rect= new
Rectangle(10,20);
rect.Display();
}
}
7.
Nested Struct
Dr NeerajKumar Pandey
struct Employee
{
public string name;
public int code;
public struct Salary
{
public double basic;
public double allowance;
}
}
struct M
{
public int x;
}
struct N
{
public M obj;//object of M
public int y;
}
N obj1;
obj1.obj.x=100;//x is a
member of obj, a member of
obj1
obj1.y=90;//y is a member
of obj1.