joydip_kanjilal
Contributor

How to use const, readonly, and static in C#

how-to
Jun 08, 20206 mins
C#Microsoft .NETSoftware Development

Understand the similarities and differences between the const, readonly, and static keywords in C#

question marks / questions
Credit: Marzavka / Getty Images

The keywords const, readonly, and static are used often when programming in C#. However, while these keywords have important differences, they also have similarities that sometimes make it hard to know when to use which. This article discusses the const, static and readonly keywords in C#, how they compare, and how we should use them in our C# applications.

To work with the code examples provided in this article, you should have Visual Studio 2019 installed in your system. If you don’t already have a copy, you can download Visual Studio 2019 here

Create a console application project in Visual Studio 2019

First off, let’s create a .NET Core console application project in Visual Studio. Assuming Visual Studio 2019 is installed in your system, follow the steps outlined below to create a new .NET Core console application project in Visual Studio.

  1. Launch the Visual Studio IDE.
  2. Click on “Create new project.”
  3. In the “Create new project” window, select “Console App (.NET Core)” from the list of templates displayed.
  4. Click Next.
  5. In the “Configure your new project” window shown next, specify the name and location for the new project.
  6. Click Create.

This will create a new .NET Core console application project in Visual Studio 2019. We’ll use this project to illustrate the use of the const, readonly, and static keywords in C# in the subsequent sections of this article.

Use the const keyword in C#

The const (read: constant) keyword in C# is used to define a constant variable, i.e., a variable whose value will not change during the lifetime of the program. Hence it is imperative that you assign a value to a constant variable at the time of its declaration.

This value of a constant variable is also known as a “compile-time” value. Variables declared using the const keyword are also known as compile-time constants. It should be noted that a constant variable is immutable, i.e., the value assigned to a constant variable cannot be changed later.

The following code snippet illustrates how you can define a compile-time constant using the const keyword in C#.

const string connectionString = "Specify your database connection string here.";

Note that you must assign a value to a constant variable at the time you define it. Note also that you cannot use the const keyword to create a constant object. The const keyword can only be applied to the primitive data types (such as ints, floats, chars, and booleans) and strings. Let’s understand the use of const with an example.

Consider the following class named Author. We’ll give the Author class only a few properties to make it simple.

public class Author
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Address { get; set; }
    }

Now if you try to create a constant object of the Author class using the const keyword, you’ll observe the compilation error shown in Figure 1 below.

csharp const 01 IDG

This error indicates that the right-hand side of the assignment operator should have a constant value to satisfy the expression. Because the statement new Author() is not a constant, the assignment is not valid and hence the error.

Use the readonly keyword in C#

The readonly keyword can be used to define a variable or an object as readable only. This means that the variable or object can be assigned a value at the class scope or in a constructor only. You cannot change the value or reassign a value to a readonly variable or object in any other method except the constructor.

Let’s understand this with an example. Consider the following class named DbManager.

public class DbManager
    {
        public readonly string connectionString =
        "Specify your database connection string here.";
        public DbManager()
        {
            connectionString = "You can reassign a value here.";
        }
        public void ReAssign()
        {
            connectionString = "This is not allowed";
        }
    }

The above code will not compile and you will be presented with the error shown in Figure 2.

csharp readonly 02 IDG

Use the static keyword in C#

The static keyword in C# can be used on a variable, a method, or an object. Note that a static member of a class belongs to the type of the object rather than to the instance of the type. In other words, static members are accessed with the name of the class, not the name of an instance. 

Consider the following class named Utility that contains a static method.

public class Utility
    {
        public static void SomeMethod()
        {
            //Write your code here
        }
    }

You cannot call the method SomeMethod() using an instance of the Utility class. Rather, you should call this method using the following syntax.

Utility.SomeMethod();

The same rule applies for a static variable or a static object. You can refer to a static member of a class only by using the syntax shown below.

ClassName.Member;

Or

ClassName.Member();

A constructor of a class can be static. A static constructor of a class is used to initialize the static members of the class. However, a static constructor of a class cannot accept parameters.

A rule for const, readonly, and static

Here is the rule of the thumb you can follow when working with the const, readonly, and static keywords. Use the const keyword when the value contained in a variable will never change during the lifetime of the application. Use the readonly keyword when you are not sure whether the value of a variable of an object needs to change but you want to prevent other classes from changing the value. Use the static keyword when you want the member of a class to belong to the type rather than to the instance of the type.

joydip_kanjilal
Contributor

Joydip Kanjilal is a Microsoft Most Valuable Professional (MVP) in ASP.NET, as well as a speaker and the author of several books and articles. He received the prestigious MVP award for 2007, 2008, 2009, 2010, 2011, and 2012.

He has more than 20 years of experience in IT, with more than 16 years in Microsoft .Net and related technologies. He has been selected as MSDN Featured Developer of the Fortnight (MSDN) and as Community Credit Winner several times.

He is the author of eight books and more than 500 articles. Many of his articles have been featured at Microsoft’s Official Site on ASP.Net.

He was a speaker at the Spark IT 2010 event and at the Dr. Dobb’s Conference 2014 in Bangalore. He has also worked as a judge for the Jolt Awards at Dr. Dobb's Journal. He is a regular speaker at the SSWUG Virtual Conference, which is held twice each year.

More from this author