Skip to content

Readonly and constant members

C# Curator

C# Curator

Asked May 24, 2009, 7:57 PM EDT1 answer
Share
LinkedInX

What are readonly and constant members? Like to have a practical and clearn understanding of it.

Thanks,

Puran

1 Answer

Know the answer? Post it. Somebody with the same question will find it here.

  • 0
    Hi,

    Constant variables are, well, constant, meaning that you can't alter their values after they're set.
    Readonly variables are like constants, but you can change their values in constructor.
    Below is a code sample:

    Code
        8   public class TestClass
    Code
        9   {
    Code
       10     const string constString = "this is a const string";
    Code
       11     readonly string readonlyString = "this is a readonly string";
    Code
       12
    Code
       13     public TestClass()
    Code
       14     {
    Code
       15       Console.WriteLine("constString value: {0}", constString);
    Code
       16       // constString = "abc"; <- can't change value, throws error
    Code
       17
    Code
       18       Console.WriteLine("readonlyString initial value: {0}", readonlyString);
    Code
       19
    Code
       20       // you can change the readonly variable value in constructor
    Code
       21       readonlyString = "new value for readonly string";
    Code
       22
    Code
       23       // output:
    Code
       24       // readonlyString new value: new value for readonly string
    Code
       25       Console.WriteLine("readonlyString new value: {0}", readonlyString);
    Code
       26     }
    Code
       27   }
    0