0
0
C Sharp (C#)programming~5 mins

Constants and readonly fields in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Constants and readonly fields let you store values that should not change after you set them. This helps keep your program safe and clear.

When you have a value that never changes, like the number of days in a week.
When you want to set a value once and never change it again, like a configuration setting.
When you want to protect important data from accidental changes in your code.
When you want to make your code easier to understand by showing which values stay the same.
Syntax
C Sharp (C#)
public const int DaysInWeek = 7;

public readonly int MaxUsers;

public MyClass()
{
    MaxUsers = 100;
}

const values must be set when declared and cannot change later.

readonly fields can be set when declared or inside a constructor, but not changed after that.

Examples
This constant holds the value of Pi and cannot be changed anywhere in the program.
C Sharp (C#)
public const double Pi = 3.14159;
This readonly field is set once in the constructor and cannot be changed later.
C Sharp (C#)
public readonly string ConnectionString;

public MyClass()
{
    ConnectionString = "Server=localhost;Database=myDb;";
}
Trying to change a const value after declaration causes a compile error.
C Sharp (C#)
public const int MaxScore = 100;

// MaxScore = 200; // This will cause an error because const cannot be changed.
Sample Program

This program shows how to use a constant and a readonly field. The constant is fixed at 7, and the readonly field is set when the object is created.

C Sharp (C#)
using System;

class Program
{
    public const int DaysInWeek = 7;
    public readonly int MaxPlayers;

    public Program(int maxPlayers)
    {
        MaxPlayers = maxPlayers;
    }

    public void ShowInfo()
    {
        Console.WriteLine($"Days in a week: {DaysInWeek}");
        Console.WriteLine($"Max players allowed: {MaxPlayers}");
    }

    static void Main()
    {
        Program game = new Program(5);
        game.ShowInfo();
    }
}
OutputSuccess
Important Notes

Use const for values that never change and are known at compile time.

Use readonly when the value is set once but only known at runtime, like from a constructor.

Trying to change a const or readonly value after initialization will cause errors.

Summary

const means the value is fixed forever and set when declared.

readonly means the value can be set once, usually in a constructor, and then stays the same.

Both help keep your program safe by preventing unwanted changes.