Understand the similarities and differences between the const, readonly, and static keywords in C# 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. Launch the Visual Studio IDE. Click on “Create new project.” In the “Create new project” window, select “Console App (.NET Core)” from the list of templates displayed. Click Next. In the “Configure your new project” window shown next, specify the name and location for the new project. 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. 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. 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. How to do more in C#: How to use data annotations in C# How to work with GUIDs in C# 8 When to use an abstract class vs. interface in C# How to work with AutoMapper in C# How to use lambda expressions in C# How to work with Action, Func, and Predicate delegates in C# How to work with delegates in C# How to implement a simple logger in C# How to work with attributes in C# How to work with log4net in C# How to implement the repository design pattern in C# How to work with reflection in C# How to work with filesystemwatcher in C# How to perform lazy initialization in C# How to work with MSMQ in C# How to work with extension methods in C# How to us lambda expressions in C# When to use the volatile keyword in C# How to use the yield keyword in C# How to implement polymorphism in C# How to build your own task scheduler in C# How to work with RabbitMQ in C# How to work with a tuple in C# Exploring virtual and abstract methods in C# How to use the Dapper ORM in C# How to use the flyweight design pattern in C# Related content feature 14 great preprocessors for developers who love to code Sometimes it seems like the rules of programming are designed to make coding a chore. Here are 14 ways preprocessors can help make software development fun again. By Peter Wayner Nov 18, 2024 10 mins Development Tools Software Development feature Designing the APIs that accidentally power businesses Well-designed APIs, even those often-neglected internal APIs, make developers more productive and businesses more agile. By Jean Yang Nov 18, 2024 6 mins APIs Software Development news Spin 3.0 supports polyglot development using Wasm components Fermyon’s open source framework for building server-side WebAssembly apps allows developers to compose apps from components created with different languages. By Paul Krill Nov 18, 2024 2 mins Microservices Serverless Computing Development Libraries and Frameworks news Go language evolving for future hardware, AI workloads The Go team is working to adapt Go to large multicore systems, the latest hardware instructions, and the needs of developers of large-scale AI systems. By Paul Krill Nov 15, 2024 3 mins Google Go Generative AI Programming Languages Resources Videos