C# Variables Tutorial For Beginners With Examples

Variables are the name given to storage locations.
Variables in C# can be of specific type. The type determines what values can be stored in that variable and what type of operations can be peformed on these values.

Declaring and Initializing Variables in C#

To declare a variable in C# the data type has to be mentioned first and then the variable.
 
  string strData;
        
A variable is initialized by declaring it and then assigning a value to it.
        
 string strData = "Welcome";
        
Multiple variables can be declared in the same line separated by commas.
 
  string strData, strName, strGender;
        
Multiple variables can be initialized in the same line separated by commas.
 
  string strData = "Welcome", strName = "Mother Teresa", strGender = "Female";
        
As shown in the below code, integer variables store number values, string variables store string values and double variables store floating point values.
 int intData = 21;
 string strData = "Welcome";
 double dblData = 95092120987.87;
        
Variables must be initialized or assigned a value before it can be used in a program.

Why it is called variable?

In a program the value of a variable can be changed multiple times. Since their values can vary so they are called variables.
A variable cannot be re-declared in C#.
A variable declared at class or struct level is called as a Field.

Explicit and Implicit Variables in C#

Explicit variables are the variables where the data type is mentioned explicitly. Below intData is an explicit variable.
 int intData = 123;
        
The variables whose type is determined by the compiler by analyzing the value assigned to the variable are implicit variables .
In the below example the compiler assigns int type to variableOne and string type to variableTwo. There is no need to explicitly specify the data types.
 var variableOne = 123;
 var variableTwo = "Welcome";
        

Naming Conventions

Microsoft suggests the following naming conventions for variables:
  • For naming variables Camel notation should be used. In Camel Notation the name should start with lowercase letters and then uppercase. Like myVariable, easyNumber etc.
  • Multiword names should not have any underscores. Variable names such as high_Value is not as per Microsoft's standard.
  • Avoid special characters like backslash or hyphens in variables.
Space is not allowed in variable names.