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

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: