Variables and Constants

October9, 2017
by admin

In the last topic we have discussed about data types in C#. In this topic we are going to discuss what are variables and constants and how to use them in C# code.

Variable:

In its simplest definition variable is nothing but a name or a label given to the memory location where our data is stored. Each variable need to be declared with a data type so that the compiler will know what type of information we are going to store in it.
There are two main steps involved in using variables. The first is a declaration and the second is an initialization.

Let’s have a look at how to declare variable in C#.

Syntax:

<data type> <variable name or label>;

or

<data type> <label list>;

As you can notice while declaring variable we have to first give data type and then name or label of the variable.

Ex:

int x;
string name;
string city;
float salary;
bool isActive;

You can also declare a number of variables on the same line if they are of same data type.

Ex:

string name, city, state, country;

You can think variable as a field type.

Let’s now look at how to initialize variable in C#. Initialization means assigning value to a variable.

Ex:

int x;
x = 59;

string name;
name = "Chittaranjan";

As you can see we have first declared variables x and name with their data type.

After declaration on the next line we have initialized variables with values by using ‘=’ assignment operator.

There are various operators available in C#. We will discuss them later in this course.

We have assigned value 59 to variable ‘x’ and “Chittaranjan” to variable ‘name’.

Note that when we declare a variable it has a default value of data type. For example, when we declared variable ’x’ with ’int’ data type, variable ’x’ was created with a default value of ’int’ data type which is 0. So it has a value 0. When we initialized variable ’x’ with value 59, a value of ’x’ became 59.

Here declaration and initialization are happening on separate lines. We can also initialize a variable at the time of declaration.

Ex:

int x = 59;
string name = "Chittaranjan";

Along with the primitive data types we can also store reference data types values to variables. We will see what are value types, reference types and custom types later in this course.

Using object data type variable:

Ex:

object o;
o = 10;
o = "Sachin";

Let’s see a simple example of how to use variable in C# coding.

Ex:

Problem:

Get a name and age from user as an input and then display them to the console output.

Solution:


  using System;

  namespace VariableDemo
  {
    class Student
    {
      static void main(string[] args)
      {
        string name;
        int age;

        Console.WriteLine("Enter your name: ");
        name = Convert.ToString(Console.ReadLine());

        Console.WriteLine("Enter your age: ");
        age = Conver.ToInt32(Console.ReadLine());

        Console.WriteLine("Your name is " + name);
        Console.WriteLine("Your age is " + age);

        Console.WriteLine("Press any key to exit");
        Console.ReadKey();
      }
    }
  }

Output:

Enter your name: Chittaranjan
Enter your age: 43

Your name is Chittaranjan
Your age is 43

Code explanation:

In the above example, we have to get ’name’ and ’age’ from user as an input. Then we need to display them to the console output. So we need two variables to store input values. For that first we have declared two variables, a variable labeled ’name’ having data type ’string’ to store the name of the user and a variable labeled ’age’ having data type ’int’ to store age of the user.

string name;
int age;

Then we took the input from the user for ‘name’ and ‘age’ and stored entered values in our variables with the following code.

Console.WriteLine("Enter your name: ");
name = Convert.ToString(Console.ReadLine());

Console.WriteLine("Enter your age: ");
age = Conver.ToInt32(Console.ReadLine());

Note that the Console.ReadLine() method returns the value as an ’object’ data type. So in order to store it in our variable we need to convert it to the variable data type. To do this we have used inbuilt conversion functions.

For converting ‘name’ value we have used Convert.ToString() since our ‘name’ is of type string. For converting ‘age’ value we have used Convert.ToInt32() inbuilt function since age is of type integer.

Once we have ’name’ and ’age’ entered by the user, we need to print entered values along with appropriate messages to console output. To do this we have written the following code.

Console.WriteLine("Your name is " + name);
Console.WriteLine("Your age is " + age); 

Note that we have used the concatenation operator (+) to join string message to the variable value. The plus (+) sign works as a concatenation operator when either of the operand is of type string. The operands are the things we placed on the left and right side of the operator. We will discuss more about operators in C# later in this course.

After displaying the ‘name’ and ‘age’ of the user we have simply asked the user to press any key to close or terminate the application with following code.

Console.WriteLine("Press any key to exit");
Console.ReadKey();

That’s all about our example code. When we compile and run the application and if there are no errors in our code then you will see the output as shown in the output section.


Constants:

You have just learnt variable. You can change the value of a variable any time within the lifetime of an application. If you want to assign a fix value to a memory location and don’t want to change it within the lifetime of an application then you need to use ’constant’.

Constant helps us to set a value once, at the time of declaration. It is known to the compiler at the time of compilation. Afterwards at runtime it cannot be changed. If the program code tries to change it error will be occurred.

To create a constant use ‘const’ keyword or modifier.

Syntax:

[access modifier] const <data type> <label> = <value>;

Ex:

public const float pi = 3.14F;

Multiple constants of the same data type can be declared on a single line.

Ex:

const days=30, month=3, year = 2017;

As you can see in the syntax we have to declare constant with access modifier such as private, public, protected, internal or protected internal. We will learn more about access modifier later in this course. Then we have to use the ‘const’ keyword or modifier. Then we have to use a data type.

Note that only built-in data types are supported by constant. It is not supported for user defined data types such as classes, structures and arrays etc.

Then we have to give a label to the constant and then assign a fix value using the assignment operator.

Lets have a look at the constant example.

Ex:

Problem:

Write a program to get a radius of a circle as an input from the user. Then calculate the area of a circle and print it to the console output.

Solution:


  using System;

  namespace ConstantDemo
  {
    class ConstDemo
    {
      static void main(string[] args)
      {
        const float PI = 3.14f;
        int radius;
        float area;

        Console.WriteLine("Enter radius of circle: ");
        radius = Convert.ToInt32(Console.ReadLine());

        area = PI * r * r;
      
        Console.WriteLine("Area of Circle: " + area.ToString());
        Console.WriteLine("Press any key to exit: ");
        Console.Readkey();
      }
    }
  }

In the above code, we have calculated the area of a circle based on the radius entered by the user. So first we have declared one constant of data type float to hold the Pi value since it is not going to change in the lifetime of our application.

const float PI = 3.14f;

Then we have declared variables labeled as ‘radius’ and ‘area’ for circle radius and area respectively.

On the next line, we have asked the user to enter the radius of a circle and store entered value in variable radius.

Now we have radius and Pi and we can calculate the area of a circle using formula as follows.

area = PI * r * r;

Here we have used multiplication operator ‘*’. We will discuss more about operators in C# later in this course.

Now we have an area of a circle in a variable ‘area’. The next thing is to display the calculated area of a circle to the user. We have done this using following line of code.

Console.WriteLine("Area of Circle: " + area.ToString());

Note here that in order to concatenate the value of ‘area’ which is of type ‘float’ to our message which is of type ‘string’, we have converted area from float to string using inbuilt ToString() function.

After printing the area of a circle to console output, we simply asked user to press any key to exit the application using the following lines of code.

Console.WriteLine("Press any key to exit: ");
Console.Readkey();

Now you have a knowledge about variables and constants and how to use them in C# code. We have seen simple code examples to understand them so that you can easily use them in c# coding.

C# Fundamentals