C# Variables
Storing data in variables.
C# Variables
Variables are containers for storing data values.
In C#, there are different types of variables (defined with different keywords), for example:
int- stores integers (whole numbers), without decimals, like 123 or -123double- stores floating point numbers, with decimals, like 19.99 or -19.99char- stores single characters, like 'a' or 'B'. Char values are surrounded by single quotesstring- stores text, like "Hello World". String values are surrounded by double quotesbool- stores values with two states: true or false
Declaring (Creating) Variables
To create a variable, you must specify the type and assign it a value:
type variableName = value;
Constants
If you don't want others (or yourself) to overwrite existing values, you can add the const keyword in front of the variable type.
This will declare the variable as "constant", which means unchangeable and read-only.
Examples
String Variable
Storing and printing a name.
using System;
class Program
{
static void Main(string[] args)
{
string name = "John";
Console.WriteLine(name);
}
}Integer Variable
Storing and printing a number.
using System;
class Program
{
static void Main(string[] args)
{
int myNum = 15;
Console.WriteLine(myNum);
}
}Change Variable Value
Overwriting a variable's value.
using System;
class Program
{
static void Main(string[] args)
{
int myNum = 15;
myNum = 20; // myNum is now 20
Console.WriteLine(myNum);
}
}