C Sharp Structs

C# Structs

To create an instance of a class in C#, classes and structs are used. Classes and structs are blueprints. Classes in C# are a reference type. The structs are however value type. Also for lightweight objects like Color, Rectangle, Point, etc., the structs are used. In case the data is not intended to be modified after the creation of struct, the struct can be useful. It can’t support inheritance but can implement interfaces.

Example 1:

using System;  
public struct rect  
{  
    public int w, h;  
 
 }  
public class Details  
{  
    public static void Main()  
    {  
        rect x = new rect();  
        x.w = 20;  
        x.h = 50;  
        Console.WriteLine("Area of Rectangle of width = 20cm and height = 50cm is " + (x.w * x.h) + " cm square");  
    }  
}

Output:

Explanation:

In the above example, we are creating a struct Rectangle. The ‘w’ and ‘h’ are the two members of a struct rectangle.

Example 2:

using System;  
public struct Square  
{  
    public int side;  
 
    public Square(int s)  
    {  
        side = s;  
    }  
    public void area() {   
     Console.WriteLine("Area of Square of side = 10cm is: "+(side*side)+ " cm square"); }  
    }  
public class Details  
{  
    public static void Main()  
    {  
        Square x = new Square(10);  
        x.area();  
    }  
}

Output:

Explanation:

In the above example, we are using a constructor to initialize data. A method is also used to calculate the area of a square.

Please follow and like us:
Content Protection by DMCA.com