Every programming language has some fundamental concepts that help programmers to store and deal with values or data. Variables and assigning values to those variables are some of them. In this tutorial chapter, you will learn about these concepts.
What Are Variables in C#?
Variables are specific names given to locations in the memory for storing and dealing with data. Values of a variable can be changed or reused as many times as possible. Every variable name has a specific type that resolves the size and layout of memory the variable will hold as well as the range of values that variable within your program can hold. Also, programmers can determine what type of operations that variable can be applied for.
Types of C# Variables
The basic types of variables that can be formed in a C# program are:
|Integral types||sbyte, byte, short, ushort, int, uint, long, ulong, and char|
|Floating point types||float and double|
|Boolean types||true or false values, as assigned|
|Nullable types||Nullable data types|
C# also permits programmers to define other types of variables and their values like the enum and reference types of variables like classes.
Define Variables in C#
For implementing variables in a C# program, you have to define them before using. To do this the syntax is:
Here data_types will be a valid data type (such as char, int, float, double or any other user-defined data type) of C# and the variable_names will be the set of variable names which are valid C# identifiers separated by commas.
char s, chrr; int a, b, c; float pi, sal; double aadharno;
Initializing Variables in C#
A C #variable gets initialized using the assignment operator which is the equal sign. We will learn more about different operators in the subsequent chapters. The syntax for initializing a variable in C# is:
<data_type> <variable_name> = value;
Some common Examples are:
char ch = 'g'; int xy = 6, roll = 42; byte b = 22; double pi = 3.14159; float salary = 20000.0f;
Accepting Values in a Program
There is a particular function of the Console class that provides the function Readline() to take input from the user for storing them in a variable, which is ultimately a named memory location.
Let us see how to use this function name with any variable to fetch (using the keyboard) and assign values to that variable:
double sal; sal = Convert.ToDouble(Console.ReadLine());
In the above code snippet, the first line will declare a variable as a double type. The second line will first execute the right side which will wait for the user to input any number and will convert the input values to double using the Convert.ToDouble() and will finally assign that value to 'sal' variable using the assignment operator (=).