Working with Variables

In this chapter you will learn:
  • How to create variable in C#?
  • How to assign value in a variable in runtime?
  • How to convert value according to types of variable?

A variable refers to the memory address. When you create variable, it creates holds space in the memory that is used for storing temporary data. As you know about c# data types, each data type has predefined size. In this chapter you will learn how to use data types to create variable.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Variable_Example
{
    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

Please enter first value
5
Enter second Value
7
Add of 5 and 7 is 12
__

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()

Summary

In this chapter, you learned about how to use variables in C# and how to assign value at runtime. You also learned about how to convert value according to types of variables. Next is example section, in which you will see someĀ  programming examples of C# data types and variables.

 

Share your thought