Variables And Data Types
Lesson 2.1: Variables and Data Types
In this lesson, you'll learn how to store and work with different kinds of data in your C# programs.
What are Variables?
Imagine variables as containers that hold values. Each container has a name (the variable's name) and a type (the kind of data it can store).
You can think of them like labeled boxes. You can put things in the boxes (store values) and take things out (retrieve values) as needed.
What are Data Types?
Data types tell the computer what kind of information a variable can hold. This is important because different types of data are stored and processed differently.
C# has several built-in data types for common kinds of information:
Data Type Description Example Value
int Stores whole numbers (integers) without decimals. 12, -35, 0
double Stores floating-point numbers (numbers with decimals). 3.14, -2.5, 0.0
string Stores a sequence of characters (text). "Hello, World!", "This is a string."
char Stores a single character. 'A', '7', '!'
bool Stores a Boolean value, which can be either true or false. true, false
Declaring and Using Variables
Declaration:
To create a variable, you declare it by specifying its data type and giving it a name:
C#
int age; // Declares an integer variable named "age"
double price; // Declares a double variable named "price"
string name; // Declares a string variable named "name"
char initial; // Declares a char variable named "initial"
bool isStudent; // Declares a bool variable named "isStudent"
Initialization (Optional):
You can also assign an initial value to the variable when you declare it:
C#
int age = 25;
double price = 9.99;
string name = "Alice";
char initial = 'A';
bool isStudent = true;
Assignment:
You can change the value stored in a variable using the assignment operator (=):
C#
age = 26; // Now the variable "age" stores the value 26
name = "Bob";
Example: Using Variables
C#
using System;
namespace VariablesExample
{
class Program
{
static void Main(string[] args)
{
string name = "Alice";
int age = 25;
double gpa = 3.75;
Console.WriteLine("Name: " + name);
Console.WriteLine("Age: " + age);
Console.WriteLine("GPA: " + gpa);
}
}
}
Output:
Name: Alice
Age: 25
GPA: 3.75
Important Considerations
Case Sensitivity: C# is case-sensitive, so age and Age would be different variables.
Meaningful Names: Choose variable names that describe the data they hold (e.g., numberOfStudents instead of n).
Let me know if you have any other questions.