Variables and Data Types
In C#, variables are used to store and manipulate data. Before using a variable, it must be declared with a specific data type. C# provides several built-in data types, including integers, floating-point numbers, characters, booleans, and strings.
Declaring Variables
To declare a variable in C#, you need to specify its data type followed by the variable name. Here are some examples:
1int age;
2string name;
3bool isEmployed;
Initializing Variables
To assign a value to a variable, you can use the assignment operator =
. Here's how you can initialize the variables:
1age = 30;
2name = "John Doe";
3isEmployed = true;
Data Types
C# supports various data types, including:
- int: Used for storing integer numbers
- double: Used for storing floating-point numbers
- char: Used for storing single characters
- string: Used for storing sequences of characters
- bool: Used for storing boolean values
Here's how you can declare and initialize variables of different data types:
1int score = 100;
2double temperature = 98.6;
3char grade = 'A';
4string message = "Hello, World!";
5bool isValid = true;
Type Inference
In C#, you can use the var
keyword to declare a variable without explicitly specifying its data type. The C# compiler infers the data type based on the assigned value. Here are some examples:
1var number = 42;
2var price = 9.99;
3var letter = 'X';
4var greeting = "Hello!";
5var status = true;
Printing Variables
To display the value of a variable, you can use the Console.WriteLine()
method. Here's an example:
1Console.WriteLine("Age: " + age);
2Console.WriteLine("Name: " + name);
3Console.WriteLine("Employment Status: " + isEmployed);
You can use the same method to print variables of different data types:
1Console.WriteLine("Score: " + score);
2Console.WriteLine("Temperature: " + temperature);
3Console.WriteLine("Grade: " + grade);
4Console.WriteLine("Message: " + message);
5Console.WriteLine("isValid: " + isValid);
Type inference can also be used when printing variables:
1Console.WriteLine("Number: " + number);
2Console.WriteLine("Price: " + price);
3Console.WriteLine("Letter: " + letter);
4Console.WriteLine("Greeting: " + greeting);
5Console.WriteLine("Status: " + status);
xxxxxxxxxx
Console.WriteLine("Status: " + status);
# Example 1: Declaring Variables
// Declare an int variable
int age;
// Declare a string variable
string name;
// Declare a boolean variable
bool isEmployed;
# Example 2: Initializing Variables
// Initialize the age variable
age = 30;
// Initialize the name variable
name = "John Doe";
// Initialize the isEmployed variable
isEmployed = true;
# Example 3: Data Types
// Declare and initialize variables of different data types
int score = 100;
double temperature = 98.6;