C# Readonly

C# Code Snippets Readonly
Share:

About

In this code snippetwe will take a look at the readonly keyword in C#.

Obviously, a variable/field marked as readonly can not be modified after it was set. However, readonly can be set at run time in the constructor or when it’s declared(at compile timeunlike const which can only be set at compile time.

Let’s have a look at the code below to see how to use readonly.

Code:

var myClass = new MyClass();

Console.WriteLine(myClass.MyProperty);
Console.WriteLine(myClass.MySecondProperty);
//Console.WriteLine(myClass.Pi); //This will not compile as consts are also static.
Console.WriteLine(MyClass.Pi); 

Console.ReadLine();

class MyClass
{
    //Readonly fields can be set when declared(at compile time) or ...
    public readonly int MyProperty = 10;
    //at run time in the constructor like MySecondProperty.
    public readonly int MySecondProperty;

    //A constatnt can only be set when declared(at compile time).
    public const float Pi = 3.14f;

    public MyClass()
    {
        //Pi = 5; //This will not compile.
        MySecondProperty = 15;
    }
}

Resulting output:

Share:

Leave a Reply

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

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger