Friday 23 December 2016

Const and Readonly in Csharp example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Const_and_Readonly_in_Csharp
{
    class DemoClass
    {
        public readonly string r_name = "asptricks.net";
        public const string c_name = "asptricks.net";
        public static string s_name = "asptricks.net";

        public DemoClass()
        {
            r_name = "www.asptricks.net";//we can initialize in constructor only
            //d_name = "www.aspricks.net";//Error CS0131  The left-hand side of an assignment must be a variable, property or indexer Const and Readonly in Csharp E:\C# Examples\Const and Readonly.
            s_name = "www.asptricks.net";
        }

    }

    class Program
    {
    
        static void Main(string[] args)
        {


            DemoClass demoObj = new DemoClass();
            //demoObj.r_name = "test.asptricks.net";//Error CS0191  A readonly field cannot be assigned to(except in a constructor or a variable initializer)  Const and Readonly.
            Console.WriteLine(demoObj.r_name);



            //Console.WriteLine(demoObj.c_name); //Error CS0176  Member 'DemoClass.c_name' cannot be accessed with an instance reference; qualify it with a type name instead Const and Readonly.
            //DemoClass.c_name = "test.asptricks.net";//Error CS0131  The left-hand side of an assignment must be a variable, property or indexer Const and Readonly in Csharp E:\C# Examples\Const and Readonly.
            Console.WriteLine(DemoClass.c_name);




            Console.WriteLine(DemoClass.s_name);
            DemoClass.s_name = "http://www.asptricks.net";
            Console.WriteLine(DemoClass.s_name);

            Console.Read();
        }
    }
}




/*
www.asptricks.net
asptricks.net
www.asptricks.net
http://www.asptricks.net
 */