Structures in C# Explained with Five Examples

Hi Programmers, welcome to new article of c#.net. this article i’ll write the program of structure in c# console application.
A struct keyword is used to create a structure. A structure can contains variables,methods,static constructor,
parameterized constructor,operators,indexer,events and property.
Syntax :
struct struct_name {
// structure members }

2.structures cannot inherit others structures or classes. see below pic.

3.Structure can implement one or more interface but the condition is members of interface must be define inside structure. see below image.

4.A structure cannot have instance property or field initializers in struct. see below image.

5.A structure is value data type.it holds various data types.suppose if you want to access employees records , use struct. see below image.

Directly Test Below Codes into Editor.

#First Employee Struct
using System;
namespace ConsoleApp2{
    class Program {
        struct Emp {
            public int empno;
            public string name;
            public string address;
            public int mob_no;
            public string designation;
        };        
        static void Main(string[] args)
        {   //Employee Second
            Emp e1;
            e1.empno = 122;
            e1.name = "Jason";
            e1.address = "Miami";
            e1.mob_no = 077788;
            e1.designation = "Marketing";
            Console.WriteLine(e1.empno); 
            Console.WriteLine(e1.name);
            Console.WriteLine(e1.address); 
            Console.WriteLine(e1.mob_no);
            Console.WriteLine(e1.designation); }
    }
}

#Second Employee Struct
using System;
namespace ConsoleApp1 {
    class Program {
         struct Emp {
            public int empno;
            public string name;
            public string address;
            public int mob_no;
            public string designation;         
        };
        static void Main(string[] args)   {
            //Employee First
            Emp e1;
            e1.empno = 121;                    
            e1.name = "Jasob";                 
            e1.address = "California";          
            e1.mob_no = 099988;                
            e1.designation = "HR";  
            Console.WriteLine(e1.empno);        
            Console.WriteLine(e1.name);
            Console.WriteLine(e1.address);       
            Console.WriteLine(e1.mob_no);
            Console.WriteLine(e1.designation); }
    }
}

Happy Coding…Thanks.

Post Author: adama