Struct in C# is a value type and a collection of variables of different data types inside a single unit. It is similar to classes in C# because both are the blueprints to create an object of a class and both are user-defined types.
However, a struct is a value type whereas a class is a reference type. Also, the struct does not support inheritance but can implement an interface. A class can have a default constructor whereas a struct cannot have a default constructor.
Syntax of struct in C#
Defining and Initialization struct in C#: The keyword that is used to define the structure is struct
. A structure can also contain constructors, constants, fields, methods, properties, indexers, etc.
Structures can be instantiated with or without new
keyword in C#.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | //Defining struct struct_name { // Fields // Parameterized constructor // Methods // Properties // Indexers ... ... }; //Initialization struct_name obj = new struct_name(); |
Consider basic data of student: name, roll, score. And also let us initialized those values by creating an instance of the struct.
Student structure is declared in the following way:
1 2 3 4 5 6 7 8 9 10 11 12 13 | //Struct Defining public struct Student { public string name; public int roll; public float score; }; //Initialization Student std = new Student(); std.name = "John Mac"; std.roll = 1101; std.score = 80.5; |
Let us go through an example to understand it better.
Example 1: C# program for structure
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | using System; public struct Student { public string name; public int roll; public float score; }; public class StructureEg { public static void Main(string[] args) { Student std = new Student(); std.name = "John Mac"; std.roll = 1101; std.score = 80.5 f; Console.WriteLine("Name: {0}", std.name); Console.WriteLine("Roll: {0}", std.roll); Console.WriteLine("score: {0}", std.score); } } |
Output:
Name: John Mac
Roll: 1101
score: 80.5
Example 2: C# program for structure using constructor and methods
It is another program where we will use a constructor and create a method for a structure.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | using System; public struct Student { public string name; public int roll; public float score; //constructor public Student(string n, int r, float s) { name = n; roll = r; score = s; } //Method public void display() { Console.WriteLine("Name: {0}", name); Console.WriteLine("Roll: {0}", roll); Console.WriteLine("score: {0}", score); } }; public class StructureEg { public static void Main(string[] args) { Student std = new Student("John Mac", 1101, 80.5 f); std.display(); } } |
Output: The result is the same as example 1 above.
Name: John Mac
Roll: 1101
score: 80.5