constant in c# language

Constant In c# Language-:  The constants refer to fixed values.The constant value can not change during the program execution . These fixed values are also called literals. Constants can be of any of the basic data types like an integer constant, a floating constant, a character constant, or a string literal.

A variable in C# can be made into a compile-time constant by adding the const keyword before the data type. This modifier means that the variable cannot be changed and it must therefore be assigned a value at the same time as it is declared. Any attempts to assign a new value to the constant will result in a compile-time error.

In other words we can say that  the Constants are data members. They are initialized at compile time using a constant expression and cannot be modified at run time. Constants are assigned a type and must be used within the context of that type. This makes constants type-safe.

Constants are usually value types, such as integer or double. A constant can be a reference type, but with limitations. Reference types are typically initialized at run time, which is prohibited with a constant. Therefore, reference types as constants must be set to null at declaration. The sole exception are strings, which are reference types but can be assigned a non-null value at declaration.

Define a constant in c#- When we are using constant in c# it is necessary to define a constant in c# language as like this way…

const <data type> <constant name> = value;

Local Constants-: A local constant must always be initialized at the same time as it is declared.

static void Main()
{
         const int a = 10; // compile-time constant
}

The const modifier creates a compile-time constant, and so the compiler will replace all usage of the constant with its value. The assigned value must therefore be known at compile-time. As a result of this, the const modifier may only be used together with the simple types, as well as with enum and string types.

Constant fields-: The const modifier can be applied to a field to make the field unchangeable.
class MyClass
{
     const int b = 5; // compile-time constant field
}

Constant fields cannot have the static modifier. They are implicitly static and are accessed in the same way as static fields.

int a = MyClass.b;

Readonly-: Another variable modifier similar to const is readonly, which creates a runtime constant. This modifier can be applied to fields, and like const, it makes the field unchangeable.

class MyClass
{
      readonly int c = 3; // run-time constant field
}

Since a readonly field is assigned at runtime, it can be assigned a dynamic value that is not known until runtime.

readonly int d = System.DateTime.Now.Hour;

Unlike const, readonly can be applied to any data type.

readonly int[] e = { 1, 2, 3 }; // readonly array

Additionally, a readonly field cannot only be initialized when it is declared. It can also be assigned a value in the constructor.

class MyClass
{
     readonly string s;
     public MyClass() { s = "Hello World"; }
}

As of C#  example the  readonly modifier can be applied to not just fields but also to structs. Declaring a struct as readonly will enforce immutability on the members of the struct, requiring all fields and properties to be made readonly.

readonly struct MyStruct
         {
            public readonly int myVar;
            public int myProperty { get; }
            public MyStruct(int var, int prop)
               {
                    myVar = var;
                    myProperty = prop;
               }
         }

Another example in c#  is the ability to mark a method’s return value as readonly when returning a value type by reference with the ref modifier. This will disallow the caller from modifying the returned value, provided that the returned value is also assigned as a readonly reference and not just a copy.

constant in c#

 Parameters -: Similar to the ref parameter modifier, C#  added the in modifier, which provides the ability to pass an argument as a readonly reference. Any code in the method that attempts to modify an in parameter (or its members in the case of a struct) will fail at compile-time and so the parameter must be initialized prior to the method call.

class MyApp
{
     static void Test(in int num)
          {
       // num = 5; // error: readonly parameter
          }
           static void Main()
                {
                  int i = 10;
                 Test(i); // passed by readonly reference
                  Test(2); // allowed, temporary variable created
               }
}

Like the ref modifier, the in modifier prevents unnecessary copies from being made of value types. This is useful for performance reasons, particularly when passing a large struct object to a method that’s called multiple times.

Constant Guideline
In general, it is a good idea to always declare variables as const or readonly if they do not need to be reassigned. This ensures that the variables will not be changed anywhere in the program by mistake, which in turn helps to prevent bugs. It also clearly conveys to other developers when a variable is intended not to be modified.

 

Leave a Comment