C C++ Java Data Structure Python JavaScript CSS Ajax PL/SQL PHP Puzzles C programs C++ programs Java programs

Home » C# programs » C# Data structure programs

Explain Structures with Example in C#

In this article, we are going to learn about structures in C#, what structures may contain, structures declarations, usages and examples.
Submitted by IncludeHelp, on January 13, 2018

A Structure is a user defines data type that contains de-similar elements of other type.

In C#, structure is a value type, that’s why, a structure occupy memory space into a stack. We can create an object or instance of object. C# structure can contain following things:

  1. Fields
  2. Properties
  3. Constants
  4. Methods
  5. Indexer etc.

A structure can also contain other structure.

Structure Declaration:

To create structure we will use struct keyword.

Syntax:

struct <struct_name>
{
	//Member of structure
}

Example:

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

Structure Object creation:

To create object or instance of structure, we will use new keyword.

Student S = new Student();

Accessing Element of structure:

To access element of structure, we use dot . Operator.

S.roll_number = 10;
S.name = "Shaurya";

program to demonstrate the use 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: 101
Name: Shaurya Pratap Singh 

In this program, we created a structure Student that contains two members, roll_number and name. And we defined two methods, one for set values to structure and other for print structure values.



Advertisements




Liked this article? Do share with your friends :)


COMMENTS