Is there a difference between readonly and { get; }

Viewed 4043

Do these statements mean the same thing?

int x { get; }
readonly int x;
6 Answers

Other answers are sorta outdated…

In newer versions of C# you can assign a default value to int x { get; } = 33; which changes things.

Basically, it gets compiled down to get-only property with a readonly private backing field. (See https://softwareengineering.stackexchange.com/q/372462/81745 for more details)

Another difference I see is that you can't use the readonly version when using interfaces as you can only define methods and properties.

readonly keyword is making sure that these variables dont change once initialised // it is equalant to making a variable private and setting getter for it. Example.

public class PlayerAuthData 
{
    public readonly string emailId, password, userName;
    private string hello;
    public PlayerAuthData(string emailId, string password, string userName)
    {
        this.emailId = emailId;
        this.password = password;
        this.userName = userName;
    }

    public string Hello 
    {
        get { return hello; }
        set { hello = value; }
    }
}

public class AuthManager
{
    void Start()
    {
        PlayerAuthData pad = new PlayerAuthData("a@a.com", "123123", "Mr.A");
        pad.Hello = "Hi there";
        print(pad.Hello);
        print(pad.password);
        print(pad.emailId);
        print(pad.userName);
    }
}
Related