c sharp Logo

C# Variables


Variables

A variable is a named storage location in the computer's memory for holding a piece of information. A variable has a name and a data type, which determines the kind of information that can be stored in it. There are several different data types in C#, such as int for integers, double for floating-point numbers, and string for text.

Here are some examples of how to declare and initialize variables in C#:

int age = 30;

double pi = 3.14159;

string name = "John Doe";

 

Constants

A constant is a variable that cannot be changed once it has been initialized. Constants are declared using the const keyword.

Here is an example of how to declare and initialize a constant in C#:

const int DAYS_IN_WEEK = 7;

 

Displaying variables

To display the value of a variable to the console, you can use the Console.WriteLine() method.

Here is an example of how to display the value of the age variable to the console:

Console.WriteLine(age);

 

Multiple variables

You can declare multiple variables of the same type in a single statement.

Here is an example of how to declare multiple variables of the type int:

int x, y, z;

 

Identifiers

An identifier is a name that is used to identify a variable, constant, method, class, or other entity in a program. Identifiers must start with a letter or an underscore (_) and can contain letters, digits, underscores, and hyphens (-).

Here are some examples of valid identifiers:

  • age
  • pi
  • name
  • DAYS_IN_WEEK
  • myVariable
  • my_variable