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

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.