Advertisement



< Prev
Next >



C# Variables, Keywords and Constants




Let's try to modify a constant value declared with const keyword in a program and see what happens.

//C# Trying to modify value of a constant
//Will issue a compile error

using System;

class A
{
public static void Main(String[] ar)
{
	//Declaring a constant with const keyword
	//And initializing it with value 10
	const int distance = 10;

	//Printing the value of a constant
	Console.WriteLine("The value of constant distance is : " + distance);
	
	//Trying to modify the value of a constant, distance
	distance = 30;
}
}


Output


A.cs(18,2): error CS0131: The left-hand side of an assignment must be a variable, property or indexer


As you can see in the output of the last program, the compiler has thrown an error stating that the left-hand side of an assignment should be either a variable, property or a indexed i.e. it cannot be a constant. So, you cannot modify a constant i.e. once you've declared at a constant using const keyword, its value is just read-only and cannot be modified.



Please share this article -





< Prev
Next >
< C# Variables, Keywords & Constants
If Statement >



Advertisement

Please Subscribe

Please subscribe to our social media channels for daily updates.


Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page




Advertisement



Notifications



Please check our latest addition

C#, PYTHON and DJANGO


Advertisement