Objects in this mirror are closer to Microsoft Technologies. DNM objective is to help users on Microsoft technologies by providing Articles, snippets, Interview Questions.

06 July 2012

Vairables in c# - Different type of variables


In this article we will discuss about variables in c#- variable definition, naming a variable, declaration and initialization of variable, different types of variables with example and finally about default values for data types.

Variable” is simply storage location of data. Variable will take different values at different time during the execution of program.

Naming a variable:
Variable name can consists of alphabets, digits and underscore. 

Following cases should be taken care of while creating a variable.
  • Should not be a reserved keyword. ( like keyword base). If we try give name with keyword then error as "Identifier is expected. 'base' is a keyword".
  • White space is not allowed between the characters.
  •  Length of name is up to 511 characters.
  • Upper case and lower case are distinct. E.g.: Variable count is different from COUNT.
  • Must not begin with digit.
Some of variable names: count, total_count, incValue,var1,Test_123.

Declaration and Initialization of variable:
[access modifier] [data type] [name] = [value];
Every variable has a type (data types) that determines what value can be stored in the variable.
Examples: 
public string name = "DotNet Mirror";
int val1, val2 = 8;  //declaration and initialization of multiple variable at a time

Different type of variables:
  • Instance variable
  • Static variable
  • Value parameters
  • Reference parameters
  • Output parameters
  • Local variables
  • Array elements
Program
Variable identification
   public class TestClass
    {
        int i;
        static int j;
        public void Sample(string k, ref int l, out int m, int[] n)
        {
            m = 20;
            int var;
        }
    }
i - instance variable
j - static variable
k - value parameter
l - reference parameter
m - output parameter
n - array element
var - local variable
 

Note:if you are using out parameter in a method that should be assigned before control leaves the current method.

Variable default values for data types:
When we declare a variable and did not assign any value then it will takes below default values.
Data type
Default value
All integer types
0
bool
True
String
Null
enum
0
decimal
0.0 m
double
0.0d
float
0.0 f
byte
0
All reference types
null


0 Comments:

Post a Comment