In c#, Variables will represent storage locations, and each variable has a particular type that determines what type of values can be stored in the variable.
C# is a Strongly Typed programming language. Before we perform any operation on variables, it’s mandatory to define a variable with the required data type to indicate what type of data that variable can hold in our application.
Following is the syntax of declaring and initializing variables in the c# programming language.
If you observe the above syntax, we added a required data type before the variable name to tell the compiler about what type of data the variable can hold or which data type the variable belongs to.
Now we will see how to define variables in our c# applications with examples.
Following is the example of using the variables in the c# programming language.
If you observe the above c# variables example, we defined multiple variables with different data types and assigned values based on our requirements.
When you execute the above program by pressing Ctrl + F5 or clicking on the Start option in the menu bar, you will get the result shown below.
If you observe the above result, we are able to print the variables in our c# application based on our requirements.
Before we declare and define variables in the c# programming language, we need to follow particular rules.
The following are some valid ways to define the variable names in the c# programming language.
The following are some of the Invalid ways of defining the variable names in the c# programming language.
In c#, we can declare and initialize multiple variables of the same data type in a single line by separating with a comma.
Following is the example of defining the multiple variables of the same data type in a single line by separating with a comma in the c# programming language.
While declaring the multiple variables of the same data type, we can arrange them in multiple lines to make them more readable. The compiler will treat it as a single statement until it encounters a semicolon (;).
Following is the simple of defining the multiple variables of the same data type in multiple lines in c# programming language.
In c#, once we declare and assign a value to the variable that can be assigned to another variable of the same data type.
Following is the example of assigning a value of one variable to another variable of the same type in c# programming language.
In c#, it’s mandatory to assign a value to the variable before we use it; otherwise, we will get a compile-time error.
If we try to assign a value of string data type to an integer data type or vice versa, as shown below, we will get an error like “cannot implicitly convert type int to string”.
This is how we can use variables in the c# programming language based on our requirements.