C# Variables

C# Variables: Storing Data

Variables are essentially "containers" for storing data values. Whenever you need your program to remember a piece of information, you store it in a variable.

C# is a strongly-typed language. This means you must explicitly declare the type of data a variable will hold when you create it.


Creating (Declaring) Variables

To create a variable, you specify the type and assign it a value:

type variableName = value;

Common Variable Types in C#:


Examples of Variables

Let's create one variable of each common type:

Variable Examples

using System;

class Program { static void Main() { int myNum = 50; double myDoubleNum = 5.99; char myLetter = 'D'; bool myBool = true; string myText = "Hello"; Console.WriteLine(myNum); Console.WriteLine(myDoubleNum); Console.WriteLine(myLetter); Console.WriteLine(myBool); Console.WriteLine(myText); } }


Constants (const)

If you want a variable to store a value that should never change throughout your program, you can use the const keyword. This creates a constant variable. If you try to change it later, C# will throw an error.

const int myNum = 15;
// myNum = 20;  <-- This would cause an error

Exercise

?

Which data type is used to store text like "Hello"?