C# struct

struct keyword is used to define a C# Structure.

Syntax of C# struct

Following is the syntax of structure in C# programming language.

</>
Copy
 struct StructureName {
 
     /* properties (constants/fields) */

     /* methods */

     /* nested types */

 }

where

  • struct is the keyword
  • StructureName is the name by which we access the C# Structure.

A structure can contain properties that are constants or fields, methods, nested types.

Example C# Structure

Following is an example structure in C#. This is a struct named Student, contains properties Name, Age; method printStudentDetails() to print the details of student and a constructor to assign the values to the object of this struct Student type.

Program.cs

</>
Copy
using System;

namespace CSharpExamples {

    struct Student{
        //properties
        string Name;
        int Age;

        //constructor
        public Student(string name, int age){
            Name = name;
            Age = age;
        }

        //methods
        public void printStudentDetails(){
            Console.WriteLine("Name : "+Name);
            Console.WriteLine("Age : "+Age);
        }
    }

    class Program {
        static void Main(string[] args) {
            Student s1 = new Student("Lini", 27);
            s1.printStudentDetails();
        }
    }
}

Output

PS D:\workspace\csharp\HelloWorld> dotnet run
Name : Lini
Age : 27

Difference between Class and Structure in C#

Now that we have come across class and structure in C#, you may be wondering, what is the difference between these two types: class and structure.

Well! The basic difference is that a class of reference type while structure is of value type.