Skip to Content
All posts

Properties In C#

2 min read ·  — #csharp-interview#junior#oop

Properties In C#

In C#, a property is a member of a class that provides a flexible mechanism to read, write, or compute the value of a private field. They are a type of class member that have accessors which define the operations to be performed on a field of the class.

Properties Syntax:

public class SampleClass
{
    private int _sampleField;

    public int SampleProperty
    {
        get { return _sampleField; }
        set { _sampleField = value; }
    }
}

In this example, SampleProperty is a property. It has a get accessor and a set accessor. The get accessor returns the value of _sampleField, and the set accessor assigns a value to _sampleField.

Auto-Implemented Properties:

C# also supports auto-implemented properties where you don't need to define a separate field.

public class SampleClass
{
    public int SampleProperty { get; set; }
}

In this case, the compiler creates a private, anonymous field that can only be accessed through the property's get and set accessors.

Read-Only Properties:

Read-only properties have a get accessor but no set accessor.

public class SampleClass
{
    public string SampleProperty { get; }
}

You can set the value of a read-only property in the constructor of the class.

Write-Only Properties:

Write-only properties have a set accessor but no get accessor. However, these are much less common.

public class SampleClass
{
    private string _sampleField;

    public string SampleProperty
    {
        set { _sampleField = value; }
    }
}

Properties with Private Setters:

You can also create a property with a private set accessor, which can only be set within the class it is defined.

public class SampleClass
{
    public string SampleProperty { get; private set; }
}

In this case, SampleProperty can be read from anywhere, but it can only be changed from within the SampleClass.

Properties with Different Access Modifiers:

C# also allows you to specify different access levels for the get and set accessors.

public class SampleClass
{
    public string SampleProperty { get; private set; }
}

In this example, the get accessor is public, but the set accessor is private.

Properties are a key part of object-oriented programming in C#, providing a way to control access to class data and allowing for more sophisticated behavior than that provided by simple data fields. In a technical interview, you may be asked to create or manipulate properties, so understanding their syntax and uses is crucial.