Explain Structures with Example in C#

In this article, we will find out about structures in C#, what structures may contain, structures presentations, uses and examples.

A Structure is a client characterizes information type that contains de-comparative components of another kind.

In C#, the structure is a value type, that is the reason, a structure consumes memory space into a stack. We can make an article or case of the item. C# structure can contain the following things:

  1. Fields
  2. Properties
  3. Constants
  4. Techniques
  5. Indexer and so forth.

A structure can likewise contain other structure.

Structure Declaration:

To make structure we will utilize struct watchword.

Syntax:

struct <struct_name>
{
	//Member of structure
}

Example:

struct Student
{
	public int roll_number;
	public string name;
}

Structure Object creation:

To make an article or occasion of structure, we will utilize new catchphrase.

Student S = new Student();

Getting to Element of structure:

To get to a component of the structure, we use the dot (.) Administrator.

S.roll_number = 12;
S.name = "Kishan";

program to show the utilization of structure in C#

using System;

namespace ConsoleApplication1
{

    struct Student
    {
        public int roll_number;
        public string name;

        public void SetValue(int roll, string na)
        {
            roll_number = roll;
            name= na;
        }

        public void printValue()
        {
            Console.WriteLine("Roll Number: " + roll_number);
            Console.WriteLine("Name: " + name);
        }
    }
    class Program
    {
        static void Main()
        {
            Student S = new Student();

            S.SetValue(101, "Shaurya Pratap Singh");
            S.printValue();
        }
    }
}

Output

Roll Number: 21
Name: Aakash Kumar Kaushik

In this program, we made a structure Student that contains two individuals, roll_number and name. Also, we characterized two strategies, one for set values to structure and other for print structure values.

Leave a Comment

error: Alert: Content is protected!!