Variables

Lesson 4
Author : Afrixi
Last Updated : February, 2023
C# - Programming Language
This course covers the basics of programming in C#.

In programming, a variable is a container that stores a value or data. In C#, variables must be declared with a specific data type, such as int (for integers), double (for floating-point numbers), bool (for Boolean values), char (for characters), or string (for sequences of characters).

Here’s an example of declaring and initializing a variable in C#:

int num = 5;

In this example, we’ve declared a variable called num of type int, and assigned it the value of 5.

We can also declare variables without assigning a value, like this:

int num;

In this example, we’ve declared a variable called num of type int, but we haven’t assigned it a value yet.

To assign a value to a variable later, we can use the assignment operator (=):

num = 10;

In this example, we’re assigning the value 10 to the variable num.

Variables can also be used in expressions and as arguments to methods. For example:

int x = 5;
int y = 10;
int sum = x + y;
Console.WriteLine(sum); // Output: 15

In this example, we’re declaring two variables x and y, assigning them the values of 5 and 10, respectively, and then adding them together and assigning the result to a variable called sum. Finally, we’re using the Console.WriteLine() method to output the value of sum to the console.

In addition to the built-in data types, we can also create our own custom data types using classes and structs. These custom data types can contain multiple variables and other data types, and can be used to represent more complex objects and structures in our programs.