#336 – Declaring and Using a readonly Field

You can make a field in a class read-only by using the readonly modifier when the field is declared.

In the example below, code that creates or uses instances of the Dog class will be able to read the SerialNumber field, but not write to it.

    public class Dog
    {
        public string Name;
        public int Age;
        public readonly string SerialNumber;

        public Dog(string name, int age, string serNumber)
        {
            Name = name;
            Age = age;
            SerialNumber = serNumber;
        }
    }

You can assign a value to a readonly field in only two different places:

  • In the class’ constructor
  • As part of the field’s declaration
        public readonly string BestFriend = "Man";
Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #336 – Declaring and Using a readonly Field

  1. Pingback: #337 – Declaring and Using Static readonly Fields « 2,000 Things You Should Know About C#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: