Difference between CONST and READONLY

Discussion in 'C#' started by nivedita2104, Sep 2, 2008.

  1. #1
    Hi,

    As per knowledge i know following differences.Please any know other please tell me


    Both are meant for constant values. A const field can only be initialized at the declaration of the field. A readonly field can be initialized either at the declaration or in a constructor. Therefore, readonly fields can have different values depending on the constructor used.
    readonly int b;
    public X()
    {
    b=1;
    }
    public X(string s)
    {
    b=5;
    }
    public X(string s, int i)
    {
    b=i;
    }
    Also, while a const field is a compile-time constant, the readonly field can be used for runtime constants, as in the following example:
    public static readonly uint l1 = (uint) DateTime.Now.Ticks; (this can't be possible with const)
     
    nivedita2104, Sep 2, 2008 IP