Tuesday, December 19, 2023

Declaring and initializing a variable

Develop On Post

In C#, you should declare a variable before using a variable.

You can declare variable using the following syntax.


{datatype} {variable-name};


int i;

Assigning a value while declaring is called Initialization.


{datatype} {variable-name} = {expession};


int i = 100;

Here the expression in the right side is of the type 'int'. So having it in the left side might feel reduntant.

C# has a feature called "Implicitly typed local variables", through which we can avoid this.


var {variable-name} = {expession};


var i = 100;

This var keyword will work only inside the code block, not at class member level.

If it is at the class member level, C# compiler will through the following error during compilation.

The contextual keyword 'var' may only appear within a local variable declaration or in script code.

No comments:

Post a Comment

Object Oriented Programming- 2- Inheritance

Inheritance is one of the fundamental attributes of object-oriented programming. It allows you to define a child class...