Table of contents
1.
Introduction
2.
Structures in C#
2.1.
Defining Structures in C#
2.2.
Example
3.
Features of Structures in C#
4.
Constructors in Structure
4.1.
Example
5.
Methods and Properties in Structure
5.1.
Example
6.
Nesting of Structures in C#
6.1.
Example
7.
Design Limitations of Structures in C#
8.
FAQs
9.
Key Takeaways
Last Updated: Mar 27, 2024

Structures in C#

Author Hari Sapna Nair
2 upvotes
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

There might arise situations where we need to store a list of information more complicated than a list of numbers in programming. For example, to represent a student, we might want the name, roll: no, age, email-id, phone number, address, marks, class, etc. This information relates to a single student entity and should be saved using a special user-defined data type. This data type is called the structure.
 

We will now learn about structures in C#, constructors in structure, features of structures, methods and properties in structure, nesting of structures, design limitations, etc.

Recommended topics, Palindrome in C# and  Ienumerable vs Iqueryable

Structures in C#

Structures in C# is a user-defined data type used to store a collection of variables with different data types under a single unit. It can contain a static constructor, parameterized constructor, indexers, constantsmethods, fields, properties, operators, events, and nested types.

Defining Structures in C#

We make use of the struct keyword to declare structures in C#. The default modifier is internal for the structure and its members. A new data type consisting of different data types is defined using the struct statement.

 

Syntax

accessModifier struct structureName {
   // Fields 
   // Constants 
   // Parameterized constructor 
   // Indexers 
   // Properties   
   // Methods 
   // Events  
}

 

To reference a field of a structure in C#, we use a "dot" operator between the variable's name and the field name of the structure.

Example

Let's see an example to understand structures better.

 

Code

using System;

struct Student {
   public string name;
   public int rollNo;
   public int marks;
};  

public class Structure {
   public static void Main(string[] args) {
      Student Student1;   /* Declare Student1 of type Student */
      Student Student2;   /* Declare Student2 of type Student */

      /* Student 1 details */
      Student1.name = "Sapna";
      Student1.rollNo = 1; 
      Student1.marks = 500;

      /* Student 2 details */
      Student2.name = "Viraj";
      Student2.rollNo = 2; 
      Student2.marks = 450;

      /* Print Student 1 details */
      Console.WriteLine("Student 1 name: {0}", Student1.name);
      Console.WriteLine("Student 1 rollNo: {0}", Student1.rollNo);
      Console.WriteLine("Student 1 marks: {0}", Student1.marks);

      /* Print Student 2 details */
      Console.WriteLine("Student 2 name: {0}", Student2.name);
      Console.WriteLine("Student 2 rollNo: {0}", Student2.rollNo);
      Console.WriteLine("Student 2 marks: {0}", Student2.marks);    
   }
}

 

Output

Student 1 name: Sapna
Student 1 rollNo: 1
Student 1 marks: 500
Student 2 name: Viraj
Student 2 rollNo: 2
Student 2 marks: 450

 

In the above example, we have declared a structure for storing the details of a student. Details like name, rollNo, and marks of the student are stored in the structure.

Features of Structures in C#

Some of the essential features of structures in C# are as follows:-

  1. Structures in C# can have fields, methods, operators, indexers, properties, methods, and events.
  2. Structures in C# can have defined constructors but not destructors. 
  3. Structures in C# cannot inherit other structures or classes.
  4. A structure in C# can implement one or more interfaces.
  5. Structure members cannot be specified as protected, abstract, or virtual.
  6. If the new operator is not used to create a structure, the fields will be unassigned, and the object cannot be used until all the fields are initialized.
  7. Structures in C# can be instantiated without using the new operator. When we create a struct object using the new operator, it gets created, and the appropriate constructor is called.

Constructors in Structure

A constructor is a special method that gets automatically invoked whenever an instance is created. It is used to assign initial values to the data members of the structure. A structure in C# cannot contain a parameterless constructor. It can only have a parameterized constructor or a static constructor. 

 

In a  parameterized constructor, we must include all the members of the structure and assign parameters to members. If any member remains unassigned, the compiler will give a compile-time error.

Example

Let's look at an example of parameterized constructor in a structure.

 

Code

using System;

struct Student {
   public string name;
   public int rollNo;
   public int marks;

  // Parameterized Constructor 
  public Student(string name, int rollNo, int marks)
    {
        this.name = name;
        this.rollNo = rollNo;
        this.marks = marks;
    }
};  

public class Structure {
   public static void Main(string[] args) {
      /* Declare Student1 of type Student */
      Student Student1 = new Student("Sapna", 1, 500);  
      
      /* Declare Student2 of type Student */
      Student Student2 = new Student("Viraj", 2, 450);  

      /* Print Student 1 details */
      Console.WriteLine("Student 1 name: {0}", Student1.name);
      Console.WriteLine("Student 1 rollNo: {0}", Student1.rollNo);
      Console.WriteLine("Student 1 marks: {0}", Student1.marks);

      /* Print Student 2 details */
      Console.WriteLine("Student 2 name: {0}", Student2.name);
      Console.WriteLine("Student 2 rollNo: {0}", Student2.rollNo);
      Console.WriteLine("Student 2 marks: {0}", Student2.marks);    
   }
}

 

Output

Student 1 name: Sapna
Student 1 rollNo: 1
Student 1 marks: 500
Student 2 name: Viraj
Student 2 rollNo: 2
Student 2 marks: 450

 

In the above example, we have used a parameterized constructor that initializes the initial value for the student.

Methods and Properties in Structure

A structure can also contain methods like in classes. These methods can be either static or non-static. But a static method can access only other static members and can't be invoked by using an object of the structure. They can be invoked only by using the struct name.
 

Note: The methods inside a structure can also be overloaded like inside a class.

Example

Let's see an example to understand how to use methods in structure. In the below example, we will use a method to say hello to a student in the class.

 

Code

using System;

struct Student {
   public string name;
   public int rollNo;
   public int marks;

  // Parameterized Constructor 
  public Student(string name, int rollNo, int marks){
    this.name = name;
    this.rollNo = rollNo;
    this.marks = marks;
  }

  public void sayHello() {
    Console.WriteLine("Hello "+name);
  }
};  

public class Structure {
   public static void Main(string[] args) {
      /* Declare student of type Student */
      Student student = new Student("Sapna", 1, 500);  
      student.sayHello();
   }
}

 

Output

Hello Sapna

Nesting of Structures in C#

C# allows us to nest one structure within another structure, using which we can create complex data types. For example, we may want to store the address of an entity student in a structure. The attribute address may also have the subparts as street number, state, city, and pin code. Hence, to store the student's address, we need to store the student's address in a separate structure and nest the structure address into the structure student.

Example

Using the example given above, let's learn how to implement nested structures in C#.
 

Code

using System;

public struct Address {
  // Data member of Address structure
  public string state;
  public string city;
}

struct Student {
   public string name;
   public int rollNo;
   public int marks;
   public Address address;

  // Parameterized Constructor 
  public Student(string name, int rollNo, int marks, string state, string city){
    this.name = name;
    this.rollNo = rollNo;
    this.marks = marks;
    // Nested structure
    address.state = state;
    address.city = city;
  }
};  

public class Structure {
   public static void Main(string[] args) {
      /* Declare Student of type Student */
      Student student = new Student("Sapna", 1, 500, "Kerala", "Trivandrum");  
     
      /* Print Student 1 details */
      Console.WriteLine("Student name: {0}", student.name);
      Console.WriteLine("Student rollNo: {0}", student.rollNo);
      Console.WriteLine("Student marks: {0}", student.marks); 
      Console.WriteLine("Student state: {0}", student.address.state);
      Console.WriteLine("Student city: {0}", student.address.city);
   }
}

 

Output

Student name: Sapna
Student rollNo: 1
Student marks: 500
Student state: Kerala
Student city: Trivandrum

Design Limitations of Structures in C#

The design limitations of structures are as follows:- 

  • We can't declare a parameter less constructor as structures in the earlier versions of C#. As it already provides an implicit parameter less constructor that produces the type's default value.
  • We can't initialize an instance property or field at its declaration in the earlier versions of C#. However, we can initialize a const or static field or a static property at its declaration.
  • A constructor of a structure type must initialize all instance fields of the type.
  • A structure type can't inherit from another class or structure type, and it can't be the base of a class. However, a structure can implement interfaces.
  • A finalizer can't be declared within a structure type.

FAQs

  1. What is the difference between classes and structures in C#?
    The difference between classes and structures in C# are as follows:-
    a. Classes are reference types, and structs are value types.
    b. Classes can have a default constructor, but structures cannot have a default constructor.
    c. Classes support inheritance, but structures do not support inheritance
     
  2. What happens when a structure in C# goes out of scope?
    When a structure in C# goes out of scope, it gets automatically de-allocated.
     
  3. When should one use structure instead of a class?
    A structure is faster than a class object as it is a value type. So we should use a structure whenever we want to store the data. However, it is easier to transfer a class object than a structure. So we must not use struct when we pass data across to other classes.
     
  4. Why are constructors used in structures in C#?
    A structure in C# can contain fields declared as private, public, internal. But we can't initialize a field inside a structure in C#. So we make use of a  constructor to initialize the structure fields.  
     
  5. How can we create a duplicate structure in C#?
    In C#, we can copy one structure object into another using the '=' (assignment)operator.

    Syntax 
     
structureObjectDestination = structureObjectSource;

Key Takeaways

In this article, we have extensively discussed the structures in C#, constructors in structure, features of structures, methods and properties in structure, nesting of structures, and design limitations. 
 

We hope that this blog has helped you enhance your knowledge regarding the structures in C# and if you would like to learn more, check out our articles on Access Modifiers in C#. Do upvote our blog to help other ninjas grow. Happy Coding!

Live masterclass