Home » C# programming

Initialization of structure in C#

In this article, we will learn about initialization of structure in C# programming. It contains structure initialization syntax, example.
Submitted by IncludeHelp, on January 16, 2018

In C# we cannot directly assign value to the members of a structure within structure like:

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

We cannot also use parameter less constructor to initialize member of structure. We can initialize member using 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(101,"Shaurya Pratap Singh");
            Student S2 = new Student(102,"Pandit Ram Sharma");

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

Output

Roll Number: 101
Name: Shaurya Pratap Singh
Roll Number: 102
Name: Pandit Ram Sharma 


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.