How to use Readonly field in C#

1 Answer

0 votes
using System;

namespace ConsoleApplication_C_Sharp
{
    class Program
    {
        class Test
        {
            readonly DateTime _dt; 

            public Test()
            {
                this._dt = DateTime.Now;
            }
            public DateTime GetDate()
            {
                return this._dt;
            }
            // Error CS0191 A readonly field cannot be assigned 
            // (except in a constructor or a variable initializer)  
            /*public DateTime SetDate()
            {
                this._dt = DateTime.Now;
            }*/
        }
        static void Main(string[] args)
        {
            Test t = new Test();

            Console.WriteLine(t.GetDate());
        }
    }
}

/*
run:
   
19/01/2017 09:25:46

*/

 



answered Jan 19, 2017 by avibootz

Related questions

1 answer 233 views
233 views asked Jul 16, 2014 by avibootz
1 answer 196 views
1 answer 205 views
1 answer 198 views
1 answer 183 views
1 answer 114 views
1 answer 158 views
...