Struct in C# | Constructors in Struct

Share

We already covered the basics of struct in C#. In this article, we will discover constructors in C# structs.

we can create a constructor in structures simply by adding a method with the same identifier name as the struct name. For example:

 struct Courses {
    public string code;

    public Courses(){
      code = "CSC367";
    }
  }

Here, we have created a parameterless constructor that assigns a value for code.

We cannot create parameterless constructors in C# version 9.0 or below.

Parameterized Constructors

For parameterized constructors, we accept argument/s in the constructor method. For example:

  struct Courses {
    public string code;

    public Courses(string _code){
      code = _code;
    }
  }

Working with constructors in struct

Example:

using System;
namespace DemoStruct {
 
  // C# struct
  struct Courses {
    public string code;
    public string uni;

    public Courses(string _code){
      code = _code;
      uni = "TU";
    }

    public void getCourse(string _code, string _uni) {
        if(_code=="CSC367"){
          Console.WriteLine("Course Title: NET Centric Computing \nCredit Hours: 3 \n{0}",_uni);
        }
    }
  }
 
  class Program {
    static void Main(string[] args) {
 
      // calls constructor of struct
      Courses course = new Courses("CSC367");
      
      // accessing struct methods
      course.getCourse(course.code, course.uni);

      Console.ReadLine();
    }
  }
}

OUTPUT

Course Title: NET Centric Computing 
Credit Hours: 3 
TU

In the above example, we have created a parameterized constructor inside the Courses struct. Inside the constructor, we have assigned the values of fields: code and uni.

Notice the line,

Courses course = new Courses("CSC367");

Like in C# classes, we are using the new keyword to call the constructor. Here, “CSC367” is an argument passed to the constructor, where it is assigned to the struct member code.

Note: We must assign the value for every field of the struct inside the parameterized constructor. For example,

  struct Courses {
    public string code;
    public string uni;
     // error
    public Courses(string _code){
      code = _code;
    }
  }

Here, we have not assigned the value for the uni field. So the code will generate an error.

Every struct has a public parameterless constructor. If you write a parameterless constructor, it must be public. If a struct declares any field initializers, it must explicitly declare a constructor.

In the next article, we will discuss about how structs are different or similar to C# class.

Reference: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/struct

Share
Sudeep Mishra

Sudeep Mishra

Healing