How to use const, readonly, and static in C# – Digitaleclub
Digitaleclub
Best for you!

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

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.

Copyright © 2020 IDG Communications, Inc.

Leave A Reply

Your email address will not be published.