Variable Initialization in C#


The syntax for variable declaration in C# is:

datatype variablelist





C# has two methods for ensuring that variables are initialized before use:
  • Variables that are fields in a class or struct, if not initialized explicitly, are by default zeroed out  when they are created. 
  • Variables that are local to a method must be explicitly initialized in your code prior to any statements in which their values are used. In this case, the initialization doesn’t have to happen when the variable is declared, but the compiler will check all possible paths through the method and will flag an error if it detects any possibility of the value of a local variable being used before it is initialized.

Example:

  public static int main()
  {  
     int mValue;

     Console.WriteLine(mValue);

    //Can`t do this , mValue need  to initialize before use

     return 0;


   }
















The same rules apply to reference types as well. Consider the following statement:

Example:

 Value  objValue





In C++, this line would create an instance of the Value class on the stack. In C#, this same line ofcode would only create a reference for a Something object, but this reference does not yet actually refer to any object. Any attempt to call a method or property against this variable would result in an error.
Instantiating a reference object in C# requires use of the new keyword. We create a reference as shown in the previous example and then point the reference at an object allocated on the heap using the new
keyword:

objValue  =  new Value();

  • Variable Declaration  in C#

Example:

  int m , k , n;
  char  c , ch;
  long mL;
  double a;

  float b;

  • Variable Initialization in C#

 int m= 10 , n = 20;  //Initialization m and n

 string name = “John”  // variable name has value  “John”

Example:

namespace Declaration
{
    class Program
    {
        static void Main(string[] args)
        {
            string firstN = " John ";
            stringlastN = "Smith";
         Console.WriteLine("Name: "+firstN +" " + lastN);
         Console.ReadLine();
        }
    }
}


No comments:

Post a Comment