How to Set Default Values for Properties in C#

Category > CSHARP || Published on : Friday, March 10, 2023 || Views: 170 || C# properties default value encapsulation class interface constructor auto-property initializers.


In C#, properties provide a way to encapsulate data and expose it through a class interface. Setting default values for properties can make our code more robust and less error-prone. In this article, we will discuss two ways to set default values for properties in C# and their differences.

In C#, properties are a way to encapsulate data and expose it through a class interface. Sometimes, it is useful to provide a default value for a property in case the user of the class does not explicitly set a value. In this article, we will discuss how to set default values for properties in C#.

One way to set a default value for a property is to initialize the property in the constructor of the class. For example:

public class MyClass
{
    private int _myProperty;

    public MyClass()
    {
        _myProperty = 0; // default value
    }

    public int MyProperty
    {
        get { return _myProperty; }
        set { _myProperty = value; }
    }
}

In the above code, we have a private field called _myProperty which is initialized to 0 in the constructor of the class. We then expose this property through a public getter and setter.

Another way to set a default value for a property is to use the C# 6 feature called "auto-property initializers". With this feature, we can initialize the property directly in the property declaration. For example:

public class MyClass
{
    public int MyProperty { get; set; } = 0; // default value
}

In the above code, we have a public property called MyProperty which is initialized to 0 directly in the property declaration.

It is important to note that when using auto-property initializers, the default value is assigned when the object is instantiated, not when the property is accessed. Therefore, if the default value is changed at some point during the lifetime of the object, the new value will be used instead.

In conclusion, setting default values for properties in C# is easy and can be done either in the constructor or using auto-property initializers. By providing default values, we can make our code more robust and less error-prone.