Tuesday, 12 April 2016

Variables in C#



A variable refers to the memory address. When you create variable, it holds space in the memory that is used for storing temporary data. As you know c# data types has predefined size. Here we will try to understand how to use data types to create variable.

using System;

namespace Variable
{
  class Program
   {
     static void Main(string[] args)
      {
        //cretaing integer type variable
        int num1, num2, result;
        //Displaying message
        Console.WriteLine("Please enter first value");
          
        //Accepting Value in num1
        num1 = Int32.Parse(Console.ReadLine());
        //Displaying message
        Console.WriteLine("Enter second Value");
        //Accepting Value
        num2 = Int32.Parse(Console.ReadLine());

        result = num1 + num2; //processing value

        Console.WriteLine("Add of {0} and {1} is {2}", num1, num2, result); //Output

        Console.ReadLine();
      }
   }
}

Output 



In the preceding example we create three integer type variable num1, num2 and result. num1 and num2 is used for accepting user value and result is used for adding both number. The new thing in the preceding example is number of placeholders.

 Console.WriteLine("Add of {0} and {1} is {2}", num1, num2, result);
If you want to display more than one variable values then you will have to assign place holder for each variables. In the preceding line {0} denotes to num1, {1} denotes to num2 and {2} denotes to result.

Conversion

C# accepts string value by default. If you are using other value then you will have to convert of specific data types.

num1 = Int32.Parse(Console.ReadLine());

You can use the following method to convert one data type to another data type.

 
 Integer = int32.parse() or Convert.ToInt32()
 Float = (float)
 Double=Convert.ToDouble()
 Decimal=Convert.ToDecimal()
 Byte=Convert.ToByte()


No comments:

Post a Comment

Featured post

What is SharePoint?

Microsoft SharePoint is an extensible platform that provides a range of products that can help organizations with solution for a variety...