Variables

A variable is nothing but a name given to a storage area that our programs can manipulate. Each variable in C# has a specific type, which determines the size and layout of the variable’s memory the range of values that can be stored within that memory and the set of operations that can be applied to the variable.

Variable: A name given to storage location in memory. Constant: An immutable value which doesn't change throughout the script or application.

The basic value types provided in C# can be categorized as −

Type

Example

Integral types

sbyte, byte, short, ushort, int, uint, long, ulong, and char

Floating point types

float and double

Decimal types

decimal

Boolean types

true or false values, as assigned

Nullable types

Nullable data types

C# also allows defining other value types of variable such as enum and reference types of variables such as class, which we will cover in subsequent chapters.

Defining Variables

Syntax for variable definition in C# is −

<data_type> <variable_list>;

Here, data_type must be a valid C# data type including char, int, float, double, or any user-defined data type, and variable_list may consist of one or more identifier names separated by commas.

Some valid variable definitions are shown here −

int i, j, k;

char c, ch;

float f, salary;

double d;

You can initialize a variable at the time of definition as −

int i = 100;

Defining float variables:

By default, c# compiler takes a value as double, when you are using real numbers. If you want a variable to be float, you have to explicitly specify as float number = 10.0f; Here, if we don’t specify f, c# compiler would treat this value as double type and it wont run, as compiler takes it as you are assigning a “double” number to a “float” number.

Note: If you don’t specify f, and declare a float value like float price = 10; it throws an error. It thinks that 10 is of double data type and you entered float data type. So, it throws an error.

Similarly to specify a decimal, you have to add m as, decimal value = 5m;

Initializing Variables

Variables are initialized (assigned a value) with an equal sign followed by a constant expression. The general form of initialization is −

variable_name = value;

Variables can be initialized in their declaration. The initializer consists of an equal sign followed by a constant expression as −

<data_type> <variable_name> = value;

Some examples are −

int d = 3, f = 5; /* initializing d and f. */

byte z = 22; /* initializes z. */

double pi = 3.14159; /* declares an approximation of pi. */

char x = 'x'; /* the variable x has the value 'x'. */

It is a good programming practice to initialize variables properly, otherwise sometimes program may produce unexpected result.

The following example uses various types of variables −

using System;

namespace VariableDefinition {

class Program {

static void Main(string[] args) {

short a;

int b ;

double c;

/* actual initialization */

a = 10;

b = 20;

c = a + b;

Console.WriteLine("a = {0}, b = {1}, c = {2}", a, b, c);

Console.ReadLine();

}

}

}

When the above code is compiled and executed, it produces the following result −

a = 10, b = 20, c = 30

Accepting Values from User

The Console class in the System namespace provides a function ReadLine()for accepting input from the user and store it into a variable.

For example,

int num;

num = Convert.ToInt32(Console.ReadLine());

The function Convert.ToInt32() converts the data entered by the user to int data type, because Console.ReadLine() accepts the data in string format.

Console.ReadLine()

returns string value but you can't perform any arithmetic operation on string variable so to convert from string to integer we use

Convert.ToInt32();

In above example we declared num as int. So, console.readline() gives string, convert it to integer using convert.toint32. Based on the num value, you can also use convert.toint16() or 32 or 64.

Declaring a variable example:

Format to declare a variable: Type identifiername = value;

Ex: int number = 1; — int is the type, number is the identifier, 1 is value and it should end with semi colon.

c# is case sensitive. number is not same as Number. You cannot use a variable unless you declare it. You cannot just say, int number and use it elsewhere in your script. You have to declare it as int number = 10; and then call it. If not it will throw an error.

To declare a constant, const float pi = 3.14;

Lvalue and Rvalue Expressions in C#

There are two kinds of expressions in C# −

  • lvalue − An expression that is an lvalue may appear as either the left-hand or right-hand side of an assignment.

  • rvalue − An expression that is an rvalue may appear on the right- but not left-hand side of an assignment.

"lvalue" and "rvalue" are so named because of where each of them can appear in an assignment operation. An lvalue can appear on the left side of an assignment operator, whereas an rvalue can appear on the right side. As an example:

int a;a = 3;

In the second line, "a" is the lvalue, and "3" is the rvalue. And in this example:

int a, b;a = 4;b = a;

In the third line of that example, "b" is the lvalue, and "a" is the rvalue, whereas it was the lvalue in line 2. This illustrates an important point: An lvalue can also be an rvalue, but an rvalue can never be an lvalue.

Add variables in output statements:

int age = 30;

int number = 10;

Double value = 18.33;

Console.WriteLine($”age is {age}, number is {number}”);

Since age , and number and value are already defined, we don’t have to define them again as int. if you want to use them with new values, directly use as age = 100, not int age =100.

These declarations like int, double are case sensitive.

Scope:

Scope is the place where your variables live. Ex:

{

byte a = 1;

{

byte b = 2;

{

byte c = 3;

}

}

}

Here a, b, c doesn’t work outside their scopes.

All the keywords like datatype names are shown in blue color in visual studio like void, int, byte, char, string etc.. For bool data type, you don’t have to enter any quotations when you update it as true or false.

Var Keyword:

We can also use keyword “var” for all your declarations. C# compiler can detect what kind of variable it is, based on the value you entered.

Ex: Instead of

int number = 5;

char firstName = “John”

You can say,

var number = 5;

var firstName = “John”

DataType search:

On your datatypes like var, int, byte, char, on windows system, place cursor on the datatype and use ctrl+ click. This will open object browser window.

On Mac, right click on data type and click goto declaration.

Last updated