#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";

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 comment