Struct in C#

You can encapsulate the small groups of related variables with the help of struct type. A struct type is a value type.
In the following example, we declare a struct with four members: name, age, class and date of birth for the any student. See the a simple struct declaration:

struct Student
 {
     public string Name;
     public int Age;
     public int ClassName;
     public datetime Dob;
 }

 
How to use struct
You can use the Student struct as:

public class Example
{
    public static void Main()
    {
      Student objStudent= new Student();
      objStudent.Name = "Ankur Gupta";
      objStudent.Age = 29;
      objStudent.ClassName= 8;
      objStudent.Dob = new DateTime(1999, 2, 13);
 
      Console.WriteLine("New student name is " + objStudent.Name);
    }
}

 
Here is also an alternative syntax for initializing structs:

public class Example
{
    public static void Main()
    {
        Student objAnkur= new Student { Name = "Ankur GUpta", Age= 29, 
                            ClassName= 8, Dob= new DateTime(1999, 2, 13)};
    }
}

 
You can also create the constructors of the struct to make it easier to use, see this:

using System;
struct Student
 {
     string Name;
     int Age;
     int ClassName;
     datetime Dob;
 
 
     public Student(string name, int age, int classname, DateTime dob)
     {
         this.Name= name;
         this.Age= age;
         this.Classname= classname;
         this.Dob= dob;
     }
 }
 
 public class Example
 {
     public static void Main()
     {
         Student objAnkur= new Student ("Ankur Gupta", 8, 29, new DateTime(1999, 2, 13));
     }
 }