C# Variables

Updated on     Kisan Patel

This tutorial will show you how to declare, initialize and use variables in C#?

When program was executed, data is temporarily stored in memory. A variable is the name given to the memory location holding the particular type of data. Each variable has associated with it a data type and a value.

Syntax

<Data Type> <Name of the variable>;

For example,

int i;
float money;
char week;

In above example, first line will reserve an area of 4 bytes in memory to store an integer type values and you can access value by the identifier i;

You can also initialize the variable when you declare it and also declare multiple variables of the same data type in one single statement.

For example,

int i = 5, j = 10, k = 15;
float money = 300.23;

C# Constant Variables

  • Constants are variables whose values, once defined, can not be changed.
  • Constant variables are declared using the const keyword.
  • Contant variables must be initialized when they are declared.

For Example,

const float PI = 3.14;

Lets take one example to understand how to declare variable and initialize in C#?

using System;

namespace VariableDemo
{
    class VariableDemo
    {
        static void Main(string[] args)
        {
            int age = 24;
            string name;
            name = "Kisan";
            Console.WriteLine(age);
            Console.WriteLine(name);
            Console.WriteLine(name + " was " + age + " years old.");
        }
    }
}

Output of the above C# program…

c-sharp-variable-demo-output


C#

Leave a Reply