C# Variables
A variable is a named storage place for a value in a C# program. Each variable has a type that states the kind of value it can hold.
Declare and print
The score variable holds a whole number. The print line shows the stored value.
using System;
class Program
{
static void Main(string[] args)
{
int score = 90;
Console.WriteLine(score);
}
}A text variable
The name variable holds text in double quotes. The print line shows the text.
using System;
class Program
{
static void Main(string[] args)
{
string name = "Hana";
Console.WriteLine(name);
}
}Change the value
The level variable first holds 1. A new value then replaces the old one.
using System;
class Program
{
static void Main(string[] args)
{
int level = 1;
Console.WriteLine(level);
level = 2;
Console.WriteLine(level);
}
}Join values in print
The plus sign joins text and values into one line. The line prints as one piece of text.
using System;
class Program
{
static void Main(string[] args)
{
string name = "Hana";
int level = 3;
Console.WriteLine(name + " is at level " + level);
}
}Example
using System;
class Program
{
static void Main(string[] args)
{
string student = "Mina";
int grade = 9;
Console.WriteLine("Student: " + student);
Console.WriteLine("Grade: " + grade);
}
}Key points
- A declaration writes a type, then a name, then a value.
- The equals sign stores the value in the variable.
- A stored value can change to a new value of the same type.
- A printed variable prints its current value.
- The const keyword marks a value that cannot change.
- Text joins with the plus sign inside a print line.
In this example, the first line prints the label Student with the name Mina. The second line prints the label Grade with the number 9. Each line joins a label and a value with the plus sign.
Note
A variable name starts with a letter in the programs in this course.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz C# Compiler
Exercise
What does the line int count = 5; do?