Constant ReadOnly and Static in C# with real life examples

C# example for constant distinguish between variable and const c# constant vs readonly asp.net const vs readonly vs static difference between const, readonly and static variable

Whether I should use Constant or ReadOnly or Static Variable, how to decide it, what are the reasons to choose Constant, ReadOnly or Static. It depends on the situation, usability and location to access. We are going to discuss each of these one by one and compare and check why we can use Constant and not the ReadOnly or Static variable. Why to use ReadOnly and not the Constant or Static variable or why we need to use the Static variable and not the Constant or ReadOnly.


Constant:

If we want to declare a variable with fixed value at the time of declaration then we can use constant. Say we want to use state "NY" in our entire class then we can declare a variable and immediately assign the value to it with "NY".

Why cannot we use ReadOnly or Static in this situation?

  1. ReadOnly variable can be used if we don't know the value at the time of declaration.
  2. Static variable can be changed which we don't want in case of constant

Some valid declaration

const string STATE = "NY";
public const Single PI = 3.14159;
public const Single PI = 22/7;
public const double GRAVITATION = 6.673e-11;
//declare multiple constants
public const int CENTURY = 100, HATRIC = 3, OVER = 6;

Valid declaration of constants with constants

 public const int c1 = 5;
 public const int c2 = c1 + 100;
 public const int c3 = c1 + c2;
 public const int c4 = c1 + c2 + c3;

Some in-valid declaration

 public const int PI = x;
 public const int PI = x/y;
 public const double DISCOUNT = (price /100 ) * 3;
 const string city = GetFromDB();
  • Value is evaluated at compile time
  • We cannot use variables to calculate the constants.
  • Constant fields and locals aren't variables
  • Constants cannot be modified
  • Constants can be of any data type or a null reference.
  • Constants are by default state so we cannot use static
  • Constants can be use to calculate the constants
  • Constants can have any access modifier
  • Constants can be accessed by using class name directy without creating instances because by default it is static, it cannot be accessed by using the instance of the class but inside the call without class name.

Some real life examples where we cannot use constant:

  • To store the price of a product
  • To store the student name
  • To store the brand name of a company
  • To store the values which we expect to change during the execution of the program

ReadOnly:

A ReadOnly variable is similar to constant but we can assign the value either at the time of declaration or in the constructor. Suppose you don't know the value at the time of declaration but you will know it at the time of initializing the object then we can use ReadOnly.

  1. If I know the value at the time of declaration then I will use constant.
  2. static variable can be changed but we don't want it in case of ReadOnly.

Some valid declaration

 public readonly int age = 27;
 public readonly single pi = 22 / 7; 

 public class Person
 {
    readonly int _age;
    public Person()
    {
        _age = GetAverageUserAge();  // from database
    }
    public Person(int age)
    {
        _age = age;
    }
 }

Invalid: try to change the readonly value in a method,

public class Age
{
    readonly int _year;
    Age(int year)
    {
        _year = year;
    }
    void ChangeYear()
    {
        _year = 1967; // Compile error.
    }
}
  • ReadOnly Value is evaluated at run time.
  • ReadOnly can be either initialized in declaration or in the constructor
  • ReadOnly cannot change the value once constructor is called.
  • ReadOnly can be used with any data type
  • ReadOnly constants can have any access modifier
  • ReadOnly property can be change by using reflection see this how

Static:

Static fields and instance fields are two of the several kinds of variables supported by C#, and at times they are referred to as static variables and instance variables, respectively. A static field is not the part of any instance of the class, no matter how many instances of a class is created, there is only one copy of the static field, let's try to understand it with an example

public  class Variable
{
    public int x = 5;
    public void test()
    {
        x = x + 5;
        Console.WriteLine(x);
    }
}

public class Exercise
{
    static void Main()
    {
        var var = new Variable();
        var.test();
        var var1 = new Variable();
        var1.test();
        Console.ReadKey();
    }
}

In this example I used x as a normal variable without static keyword, it will give the result 10 and 10

public  class Variable
{
    public static int x = 5;
    public void test()
    {
        x = x + 5;
        Console.WriteLine(x);
    }
}

public class Exercise
{
    static void Main()
    {
        var var = new Variable();
        var.test();
        var var1 = new Variable();
        var1.test();
        Console.ReadKey();
    }
}

Now we used static keyword to declare the x variable, run the application and we will get 10 and 15 as a result.

It shows the static variable value shared among all the instances of the class.

  • Static field property and method can directly accessed by using the class name.
  • Static field, property and method cannot be accessed by using the instance.
  • Static field is shared for entire instances as we already checked with example.
  • Can be used where we only want to play on the passed values
  • Best example is Math class and it's methods.
  • See this for static class Static Class in C# why and when with examples
Ali Adravi Having 13+ years of experience in Microsoft Technologies (C#, ASP.Net, MVC and SQL Server). Worked with Metaoption LLC, for more than 9 years and still with the same company. Always ready to learn new technologies and tricks.
  • constact
  • readonly
  • static
  • c#
  • oops
By Ali Adravi On 03 Apr, 15  Viewed: 3,167

Other blogs you may like

default value for different data type in C#

In C# there are different data type and they use some default value when we declare a variable. When we define a variable of type int or Int32 say int score; so what is the value of score, will it be null or zero, in the same way if we create a variable of type string/String what value it holds... By Ali Adravi   On 27 Mar 2013  Viewed: 1,263

enum in C# and conversion

An enumeration type (also known an enumeration or an enum) provides an efficient way to define a set of named integral constants that may be assigned to a variable to make programming clear, understandable and manageable. There are ways of using, like how to use enum in switch and case statement,... By Hamden   On 27 Mar 2013  Viewed: 2,215

Dynamic vs var in C# with example

When we have var which dynamically holds any type or value so why we need dynamic type, what are the differences and situations where we can use dynamic rather than var, there were some question in my mind so I explored more which I want to share here. There are two things, static type and... By Nathan Armour   On 26 Mar 2013  Viewed: 1,828

Array in C# - single, multiple and jagged array

An array can be initialized in several ways, it can store a single value or series of values, every element must be set of same type, C# supports single-dimensional arrays, multidimensional arrays (also call rectangular array) and array-of-arrays (referred jagged arrays), let’s discuss features of... By Ali Adravi   On 24 Mar 2013  Viewed: 2,054

XmlDocument Vs XDocument and their usage

When there was XmlDocument why we need XDocument, is there any better feature available with XDocument, answer is yes, XDocument has a number of benefits, easy to create, easy to update, easy to search, ability to use LINQ to XML, cleaner object model etc. In this post we will see some examples... By Ali Adravi   On 16 Mar 2013  Viewed: 972