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.






Quick links:
C FAQ(s) C Advance programs C/C++ Tips & Tricks Puzzles JavaScript CSS Python Linux Commands PHP Android Articles More...

Was this page helpful? Please share with your friends...

Are you a blogger? Join our Blogging forum.




Comments and Discussions





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 (2015-2018), Some rights reserved.