Export (0) Print
Expand All

Variables and Constants

Visual Studio 2008

A variable represents a numeric or string value or an object of a class. The value that the variable stores may change, but the name stays the same. A variable is one type of field. The following code is a simple example of how to declare an integer variable, assign it a value, and then assign it a new value.

int x = 1;  // x holds the value 1
x = 2;      // now x holds the value 2

In C#, variables are declared with a specific data type and a label. If your programming background is in loosely typed languages such as JScript, you are used to using the same "var" type for all variables, but in C# you must specify whether your variable is an int, a float, a byte, a short, or any of the more than 20 different data types. The type specifies, among other things, the exact amount of memory that must be allocated to store the value when the application runs. The C# language enforces certain rules when converting a variable from one type to another. For more information, see Built-in Data Types.

int answer = 42;
string greeting = "Hello, World!";
double bigNumber = 1e100;

System.Console.WriteLine("{0} {1} {2}", answer, greeting, bigNumber);

A constant is another type of field. It holds a value that is assigned when the program is compiled, and never changes after that. Constants are declared using the const keyword; they are useful for making your code more legible.

const int speedLimit = 55;
const double pi = 3.14159265358979323846264338327950;

A readonly variable is like a constant but its value is assigned when a program starts up. This allows you to set the value based on some other condition that you don't know until the program is running. But after that first assignment, the value cannot change again while the program is running.

Community Additions

ADD
Show:
© 2015 Microsoft