Initialization of structure in C#

In this article, we will find out about instatement of structure in C# programming. It contains structure introduction syntax, example.

In C# we can’t straightforwardly dole out value to the individuals from a structure inside a structure like:

struct Student
{
	int roll_number = 101;      //Error
	string name = "Shaurya";     //Error
}

We can’t likewise utilize parameterless constructor to instate individual from the structure. We can introduce part utilizing parameter constructor.

Example:

using System;
using System.Collections;

namespace ConsoleApplication1
{

    struct Student
    {
        public int roll_number;
        public string name;

        public Student( int x, string s)
        {
            roll_number = x;
            name = s;
        }
        
        public void printValue()
        {
            Console.WriteLine("Roll Number: " + roll_number);
            Console.WriteLine("Name: " + name);
        }
    }
    class Program
    {
        static void Main()
        {
            Student S1 = new Student(203,"Aakash Kumar Kaushik");
            Student S2 = new Student(204,"Kishan Kumar Kaushik");

            S1.printValue();
            S2.printValue();
        }
    }
}

Output

Roll Number: 203
Name: Aakash Kumar Kaushik
Roll Number: 204
Name: Kishan Kumar Kaushik

Leave a Comment

error: Alert: Content is protected!!