C# struct

In the previous section, you have understood that how a class works. In C# structures are just like as classes with some difference. A structure can have

  1. Private Fields
  2. Public properties
  3. Constructors
  4. Methods
  5. Indexers
public struct Student
{
    string _firstName = string.Empty;  // struct field
    string _lastName = string.Empty;    // struct field
    private string _fullName = string.Empty;  // struct field
    int _age = 0; // struct field
 
    public string FirstName { get; set; } // Auto implemented FirstName property of struct Student
    public string LastName { get; set; } // Auto implemented LastName property of struct Student
 
    public Student() //Constructor of Student struct, Constructor name must be same as struct name.
    {
 
    }
 
    public Student(string firstName, string lastName) //Parameterized Constructor of Student struct, Constructor name must be same as struct name.
    {
        _firstName = firstName;
        _lastName = lastName;
    }
 
    public void PrintStudentDetail(string firstName, string lastName)  //Method or function
    {
        Console.WriteLine("Student first name is : {0} and student last name is : {1}", firstName, lastName);
    }
 
    public string FullName { get; set; } //Read/Write property
    public string FirstName { get;  } //Read Only property
    public string LastName { set; } //Write Only property
}

We can create the object of a structure just like as we do for classes. We can use the Properties, member variables methods etc in the similar fashion also.

The structure is basically a value type which is used to enhance the performance and clarity of code, it also takes less memory than classes. A structure does not follow the inheritance concept, it can not inherit a structure or a class. However, a structure can implement the interface.

Uses

In the following example, the Student structure has been used to demonstrate that how you can create an object of a structure, how to use properties and methods etc.

Example

Try It
using System;
 
namespace TutorialsLeader
{
    public class MyFirstClass
    {
        public static void Main()
        {
            Student student = new Student(); // Default constructor called while creating the object of Student structure
 
            student.FirstName = "Jhon";  // Setting the values of different properties;
            student.LastName = "Doe";
            student.FullName = "Jhon Doe";
 
            student.PrintStudentDetail("Jhon", "Doe"); // calling PrintStudentDetail method of Student structure using student object.
        }
    }
}

It's also important to remember that because the structure is a value type, it can not have a destructor.

Let's learn about the differences between a struct and class in the next section.