C# Keywords Tutorial Part 38: get

C# Keywords Tutorial Part 38: get

C# is a powerful and versatile programming language that has a wide range of features to offer developers. One such feature is the “get” keyword, which is used to retrieve the value of a variable or property. In this blog post, we will explore the “get” keyword in C# with code examples to help you understand how it works.

What is the “get” keyword in C#? The “get” keyword is a part of the C# language syntax that is used to retrieve the value of a variable or property. It is typically used in conjunction with the “set” keyword to define a property, which allows the user to get and set the value of the property. The “get” keyword is used to access the value of the property, while the “set” keyword is used to set the value of the property.

Code examples of the “get” keyword: Let’s take a look at some code examples to see how the “get” keyword is used in C#.

Example 1: Using the “get” keyword with a property

public class Person
{
    private string name;

    public string Name
    {
        get
        {
            return name;
        }
        set
        {
            name = value;
        }
    }
}

In this example, we have defined a “Person” class with a “Name” property. The “Name” property has a “get” accessor that returns the value of the “name” field, and a “set” accessor that sets the value of the “name” field.

Example 2: Using the “get” keyword with an auto-implemented property

public class Person
{
    public string Name { get; set; }
}

In this example, we have defined a “Person” class with a “Name” property that is automatically implemented. The “get” accessor returns the value of the “Name” property, while the “set” accessor sets the value of the “Name” property.

Example 3: Using the “get” keyword with a read-only property

public class Person
{
    private readonly string name;

    public Person(string name)
    {
        this.name = name;
    }

    public string Name
    {
        get
        {
            return name;
        }
    }
}

In this example, we have defined a “Person” class with a read-only “Name” property. The “Name” property has a “get” accessor that returns the value of the “name” field, but it does not have a “set” accessor, which means that the “Name” property can only be set once during object initialization.

Share this post

Leave a Reply

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