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 What is Rust? Safe, fast, and easy software development Unlike most programming languages, Rust doesn't make you choose between speed, safety, and ease of use. Find out how Rust delivers better code with fewer compromises, and a few downsides to consider before learning Rust. By Serdar Yegulalp Nov 20, 2024 11 mins Rust Programming Languages Software Development how-to Kotlin for Java developers: Classes and coroutines Kotlin was designed to bring more flexibility and flow to programming in the JVM. Here's an in-depth look at how Kotlin makes working with classes and objects easier and introduces coroutines to modernize concurrency. By Matthew Tyson Nov 20, 2024 9 mins Java Kotlin Programming Languages analysis Azure AI Foundry tools for changes in AI applications Microsoft’s launch of Azure AI Foundry at Ignite 2024 signals a welcome shift from chatbots to agents and to using AI for business process automation. By Simon Bisson Nov 20, 2024 7 mins Microsoft Azure Generative AI Development Tools news Microsoft unveils imaging APIs for Windows Copilot Runtime Generative AI-backed APIs will allow developers to build image super resolution, image segmentation, object erase, and OCR capabilities into Windows applications. By Paul Krill Nov 19, 2024 2 mins Generative AI APIs Development Libraries and Frameworks Resources Videos