C# Keywords Tutorial Part 81: struct

C# Keywords Tutorial Part 81: struct

In C#, the struct keyword is used to define value types that can contain data members and methods. Unlike reference types such as classes, value types are stored directly in memory, making them more efficient in terms of performance. In this blog post, we will explore the struct keyword in more detail and provide code examples to help you understand its usage.

Defining a Struct

To define a struct in C#, you use the struct keyword followed by the name of the struct. Inside the struct, you can define data members and methods, just like you would in a class. Here is an example:

struct Person
{
    public string Name;
    public int Age;
    
    public void PrintDetails()
    {
        Console.WriteLine("Name: " + Name);
        Console.WriteLine("Age: " + Age);
    }
}

In this example, we define a struct called Person with two data members (Name and Age) and a method (PrintDetails) that prints the details of a person. Note that we use the public access modifier to make the data members and method accessible from outside the struct.

Creating an Instance of a Struct

To create an instance of a struct, you use the new keyword followed by the name of the struct. Here is an example:

Person john = new Person();
john.Name = "John";
john.Age = 30;
john.PrintDetails();

In this example, we create an instance of the Person struct called john, set its Name and Age data members, and call its PrintDetails method to print its details.

Passing a Struct as a Parameter

When you pass a struct as a parameter to a method, a copy of the struct is created and passed to the method. This means that any changes made to the copy inside the method will not affect the original struct. Here is an example:

void ChangeAge(Person person, int newAge)
{
    person.Age = newAge;
}

Person john = new Person();
john.Name = "John";
john.Age = 30;
ChangeAge(john, 35);
john.PrintDetails();

In this example, we define a method called ChangeAge that takes a Person struct and an int as parameters. Inside the method, we change the Age data member of the struct to the new age. We then create an instance of the Person struct called john, set its Name and Age data members, and call the ChangeAge method with john and 35 as parameters. Finally, we call the PrintDetails method of john to print its details. Note that even though we changed the age of john inside the ChangeAge method, the original john struct was not affected.

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *