C# Structs

In C#, Structs are like classes but they are used to create light weight objects like color, Rectangle, etc. Structs are value type unlike classes that are reference type. Using structs is useful if you have data that is not intended to be modified after creation of struct. Let's see an example of Structs

using System;
public struct Calculation 
{
            public void square (int n)
            {
                        Console.WriteLine(n+" X "+n+" = "+n*n);
            }
            public void cube(int n)
            {
                        Console.WriteLine(n+" X "+n+" X "+n+" = "+n*n*n);
            }
            public static void Main (string[] args)
            {
                        Calculation c=new Calculation();
                        c.square(100);
                        c.cube(9);
            }
}
Output
100 X 100 = 10000
9 X 9 X 9 = 729
C# Struct Example 2: Using Constructors
using System;
public struct Student
{
            int roll_no;
            string name;
            public Student(int roll_no,string name)
            {
                        this.roll_no=roll_no;
                        this.name=name;
            }
            public void display()
            {
                        Console.WriteLine(roll_no+" "+name);
            }
            public static void Main(string[] args)
            {
                        Student s=new Student(101,"Rohan Kumar");
                        s.display();
            }
}
Output
101 Rohan Kumar



ADVERTISEMENT
ADVERTISEMENT