Mark As Completed Discussion

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:

TEXT/X-CSHARP
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:

TEXT/X-CSHARP
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:

TEXT/X-CSHARP
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:

TEXT/X-CSHARP
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:

TEXT/X-CSHARP
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:

TEXT/X-CSHARP
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:

TEXT/X-CSHARP
1Console.WriteLine("Number: " + number);
2Console.WriteLine("Price: " + price);
3Console.WriteLine("Letter: " + letter);
4Console.WriteLine("Greeting: " + greeting);
5Console.WriteLine("Status: " + status);
C#
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment