Using Structure in C#

A structure is a value type data type.A structure is used when we want a single variable to hold related data of various data types. struct keyword is used to create a structure.

The syntax for Structure is:
 
<modifiers> struct <struct_name>
{
//Structure members
}
 
The modifier can be private, public or internal.

The objects of a struct can be created by using the new operator as follows.    

Structexample se = new Structexample(); 

Like classes ,structure contain data members which are defined within the declaration of the structure.However Structure differs from classes in the following way:
  • Structure are value type and they get stored in a stack.
  • Structure do not support inheritance.
  • Structure cannot have default constructor.

The following program holds the Branch details structure:

using System;
namespace sturctexample
{
    public struct branch_details
    {
        public string branch_name;
        public int strength;
        public string head_of_department;
        public string topper_of_branch;
    };
    class structure
    {
        static void Main(string[] args)
        {
            branch_details obj = new branch_details();
            obj.branch_name = "computer science and engineering";
            obj.strength = 100;
            obj.head_of_department = "Mr. john";
            obj.topper_of_branch = "fernandis";
            Console.WriteLine("Branch name is {0}", obj.branch_name);
            Console.WriteLine("Strength of branch is {0}", obj.strength);
            Console.WriteLine("Head of department is {0}", obj.head_of_department);
            Console.WriteLine("Topper of the Branch is {0}", obj.topper_of_branch);
            Console.Read();
        }
    }
}

The struct branch_details holds related data namely: branch_name,strength,head_of_department, and topper_of_branch which are of various data types.
Ebook Download
View all
Learn
View all