Topic : Variable / Identifiers in C# Programming Language:

What is Variable?

A Variable is a location in computer memory where we can store and retrieve a value. our computer's memory can be thought of as a series of cubbyholes lined up in a long row. Each cubbyhole is numbered sequentially. The number of each cubbyhole is its memory address.

Variable have address and are given name to describe their purpose. In simple program, we could create a variable named age to hold the student age and we can assign it value. A variable is a label on a cubbyhole so that it can be accessed without knowing the actual memory address.



computer Memory

Each Variable in C# has a specific type, which determines the size and layout of the variable's memory the range of values that can be stored within that memory and the set of operations that can be applied to the variable. The basic value type provided in C# can be categorized as:

TypeExample:
Integral typessbyte, byte, short, int, uint, long, ulong, and char. ( Read more... )
Floating PointFloat and Double. ( Read more... )
Decimal typesDecimal. ( Read more... )
Boolean types.true or false values, as assigned. ( Read more... )
Nullable typesNullable data types. ( Read more... )


C# also allows defining other value types of variable such as enum and reference types of variables such as Class, we will cover these topic in subsequent Tutorials.



Variable Naming Conventions:

An Variable starts with a letter A to Z or a - z, an underscore (_) or at (@) symbol.


C# is case sensitive Programming language, thus, "InfoBrother" and "infobrother" are two different Identifiers or variables in C#.


While Mathematicians are content with giving their variables one-letter names like X, Programmers should use longer, more descriptive variable names, such as Altitude, sum, user-name are better than the equally permissible a , s, and u. A variable name should be related to its purpose within the program. Good variable names make programs more readable by humans.

Identifiers can have Nearly any name, bu a few restrictions apply. here are some rules to follow when creating identifiers.



  • Rules to Create Variables/Identifiers;

    » An identifiers must start with a letter or an underscore.
    » After the first character, it may contain numbers, letters, connectors, etc.
    » We can't use keyword as an identifiers.
    » if we are using keyword as an identifiers , it must be start with "@" at symbol.



Defining Variables:

Before we can use a variable, we need to tell the compiler about it by defining it, the compiler is very picky about being told about the things in advance. to define any variable, we use this syntax:


<Data_type>    <variables>;


Here Data-type must be a valid C# data type including char, int, float, double, or any user-defined data type, and "variable" may consist one or more identifier names separated by commas.

Some Valid variable definitions are:


int age, number;       //variable to store Anyone age and number;
char name;           //character variable;
float f, percent;   //two variables to store floating numbers.
double pi;     //variable to store the value of Pi;


Initializing Variables:

A Variable can be initialized (Assigned a value to variable) Using Equal sign ( = ) sign followed by a constant expressions. we can assign a value to variable during its declaration or we can initialized it whenever we need it to initialize. The Genera form of Initialization is:


 /* <Data_Type>  <Variable_Name>  =   <value> */

//Example: 

int number = 15; //assign value 15 to "Number" at declaration time.

// or
int number;
number = 15;   //assign value later, whenever we need.


It is a Good Programming practice to initialize variables properly, otherwise sometimes program may produce unexpected results:



Let's have an example, where we will use different types of variable and will assign values.


/*Example: Variable In C#: InfoBrother: */

using System;

namespace variables
{
    class Program
    {
        static void Main(string[] args)
        {
            //initialization at same time;
            int age = 10;     //an int variable to store integers.
            string name = "Omar";   //string variable to store text:
            char language = 'c';    //char variable to store any single character.
            float max = 78.5f;     //float variable to store floating numbers.

            Console.WriteLine(" //Initialization at Declaration time:");
            Console.WriteLine(" {0} is {1} years old" ,name, age);
            Console.WriteLine(" And he Got {0}% Marks in {1}# Programming", max, language);

            //initialization whenever we need.
            int x, y, z;
            x = 12;
            y = 20;
            z = x + y;

            Console.WriteLine("\n\n //Initialization Whenever we need:");
            Console.WriteLine(" {0} + {1} = {2}", x, y, z);
            Console.ReadKey();

        }
    }
}


Read Value From User:

Our Program can read a value from user too. The Console Class in the System Namespace provides a function ReadLine() for Accepting input from the User and Store it into a Variable.

Let's have an example here:


/*Example: Variable In C#: InfoBrother: */

using System;

namespace variables
{
    class Program
    {
        static void Main(string[] args)
        {
            //string type variable to get name from user:
            string name;    

            Console.WriteLine("What's your Name? ");

            //User Need to Enter his/her Name here:
            name = Console.ReadLine();  

            Console.WriteLine("Hello Mr "+ name +".");



            //integer type variable to store integers:
            int x;       
            Console.WriteLine("\n\nPlease Enter the Value of X: ");

            /* We need to convert int to string: Because 
             the method "Readline" Accept only string type data: */

            x = Convert.ToInt32(Console.ReadLine());  //convert int to string: 
            Console.WriteLine("The Value of X is: " + x);

            Console.ReadKey();                
        }
    }
}


In Above Example, Our Program is able to get the data from user and store it into the variable. the method ReadLine() accepts Only the data in String Format. that's why we convert our integer data to string format using Convert.toint32 function.



Lvalue and Rvalue Expressions in C#:

  • There are two kinds of Expressions in C#:

    » Lvalue: An Expression that May appear as either the Left hand or right hand side fo an Assignment.
    » Rvalue: An Expression that appear on the Right hand side of Assignment. But not on the Left hand side or Assignment.

    Variables are Lvalues and Hence they may appear on the left-hand side of an Assignment. Numeric literals are Rvalues and Hence they may not be Assigned and can not appear on the left-hand side. The Example is:

    //valid 
    int x = 20;
    
    //not Valid
    20 = 20;   
















I Tried my Best to Provide you complete Information regarding this topic in very easy and conceptual way. but still if you have any Problem to understand this topic, or do you have any Questions, Feel Free to Ask Question. i'll do my best to Provide you what you need.

Sardar Omar.
InfoBrother





WRITE FOR INFOBROTHER

Advertising






Advertisement