C# Basics

C# Variables

What Is a Variable?

C# variable is something you want the computer to remember while your program is running. Computer programs need places to store and process this information while working with it. These places are called variables because the information stored there can change, or vary, during program execution. C# variables are considered the primary method for moving information around.

Note: C# variables are case-sensitive.

Variable in Short

  • According to the dictionary, a variable is anything that is not consistent.
  • “Variable” is the name given to a computer memory location for storing data that can be reused throughout the program—that is, it is used to store, retrieve, and modify changeable data.
  • A variable is always defined by a datatype, which means that it will hold the value of a specific type, such as string, int, float, and so on.
  • A value must be assigned to a variable before using it to avoid a compile-time error.

C# Variable Naming

You can’t just choose any sequence of characters as a variable name. Instead, C# has some rules regarding variable names that must be followed:

  • camelCase for local variables, such as cost, orderDetail, dateOfBirth, and firstName
  • A meaningful or descriptive name that is neither too long nor too short to identify the information stored in a variable just by looking at it
  • Can contain the letters a–z and A–Z, the numbers 0–9, and the underscore (_) character—other symbols are not allowed
  • No spaces and cannot start with a number
  • Cannot use a word reserved by C# language—keywords such as namespace, class, using, and so on

You can name a variable like a keyword by adding a prefix to the name: the at symbol (@).
Example: @namespace, @class, @using, etc.

Valid Names

  • cost, name, order, order1, _order1, income
  • order_Detail, orderDetail, dateOfBirth, hourlyRate, firstName, first_Name, isValid

Invalid Names

  • 1 (number)
  • class, while, if, protected (keyword)
  • 1order, 1name (starts with a number)

Syntax to Declare and Instantiate Using Two Statements

Create a variable by declaring its type and then giving it a name using the syntax below.

When you declare a variable, the computer knows that it has to reserve a place in its memory for this variable.

datatype variableName; // declaration syntax

To initialize a variable, you need to assign it a value. This is done by naming the variable followed by an equal sign (=) and then the value.

variableName = variableValue; // initialization syntax

Note: The term initialize means to assign an initial value.

Declaration and Instantiation Combined on a Single Line

While you can declare a variable and assign it a value in two separate steps, it is also possible to do both of them at the same time on a single line:

datatype variableName = variableValue; // syntax

Here, datatype must be one of the valid data types, and variableName is the identifier used for the variable. This is an explicitly typed local variable where the type is explicitly defined.

string name;
int age;
int weight;
bool isMarried;

Run Demo

You can define many variables in the same C# statement by specifying them in the form of a comma-separated “,” list if they are of the same type.

int age, weight;
// OR
int age,
    Weight;

Use semicolon (;)-separated C# definition statements if they are of different types.

string name; int age, weight; bool isMarried = true;

Definite Assignment

C# enforces a definite assignment policy. This means that you will need to initialize the local variable with the value before using it. Suppose the following is written:

Console.WriteLine(name); //Error : Use of unassigned local variable 'name'

Run Demo

Error: Use of unassigned local variable ‘name’

If you try to use a variable that hasn’t been declared, your code won’t compile. In this case, the compiler will tell you that something is wrong. Trying to use a variable without assigning it a value also causes an error.

In order to initialize the variable with a value, you simply have to use the assignment operator “=”. The variable name is on the left side of the operator and on the right side is the value in the following manner.

name = "Pirzada";
age = 35;
weight = 70;
isMarried = true;

Run Demo

Once a variable has been declared with a type, it cannot be redeclared with a new type, and it cannot be assigned a value that is not compatible with its declared type. For example, you cannot declare an int and then assign it a Boolean value of True/False.

age = true; //Error : Cannot implicitly convert type 'bool' to 'int'

Error: Cannot implicitly convert type ‘bool’ to ‘int’

If I try to assign a string to an age variable, it is declared an int datatype.

age = "Pirzada";
// OR
age = name;

Run Demo

The above statement will give a compile-time error because the string value cannot be assigned to an int type variable.

You can combine the declaration and initialization statements at the same time on the same line as shown below, which is more convenient.

string name = "Pirzada";
int age = 35;
int weight = 70;
bool isMarried = true;

Run Demo

You can also use a mathematical expression.

int wowExp = (3 + 2) * 4;

//Print Value
Console.WriteLine(wowExp); // 20

Run Demo

The right side is being evaluated and then assigned to the variable on the left. Meaning 3+2 is 5 and 5 * 4 is 20, which will be assigned to the wowExp variable.

Use of variables in the mathematical expression.

int a, b, c;
a = 3;
b = 2;
c = 4;

int wowExp = (a + b) * c;

//Print Value
Console.WriteLine(wowExp); // 20

Run Demo

OUTPUT

20

You can also assign the same value to multiple different variables all at the same time.

int a, b, c;
a = b = c = 786;

//Print Values
Console.WriteLine(a); // 786
Console.WriteLine(b); // 786
Console.WriteLine(c); // 786

Run Demo

OUTPUT

786
786
786

Using Type Inference

C# 3.0 introduced the implicitly typed variable with the var keyword. Now you can declare a local variable without giving an explicit or real type. The variable still receives a type at compile time, but the type is provided by the compiler.

Actually, the var keyword instructs the compiler to infer the type of variable from the expression on the right side of the initialization statement. It just means that the compiler determines and assigns the most appropriate type.

var variableName = variableValue; // Syntax

var is optional, and it’s just for convenience.

Let’s use the same C# variables as above.

var name = "Pirzada";
var age = 35;
var weight = 70;
var isMarried = true;

Run Demo

Now the variables are implicitly typed local variables, meaning that you don’t have to explicitly specify the type. The compiler determines and assigns the most appropriate type. Double quotes indicate a string variable, single quotes indicate a char variable, and the true and false values indicate a bool type.

Suggestion: Using var is convenient, but use it only when the type is obvious from the right side of the assignment.

subscribe to codebuns.com

A literal number with a decimal point is inferred as double unless you add the M/m suffix to indicate a decimal variable or the F/f suffix to indicate float variable.

var income = 24899.45m;
var hourlyRate = 20.8f;

//Print Type
Console.WriteLine(income.GetType());
Console.WriteLine(hourlyRate.GetType());

//Print Values
Console.WriteLine(income);
Console.WriteLine(hourlyRate);

Run Demo

To initialize hourlyRate, you need to add f as a suffix after 20.8 to explicitly tell the compiler to change 20.8 to a float. Similarly, to initialize income, you need to add m as a suffix to change 24899.45 into a decimal type.

A few rules you need to follow:

  • var can only be declared and initialized in a single statement. Otherwise, the compiler doesn’t have anything from which to infer the type.
  • var cannot be used on fields at class scope.
  • The initializer cannot be null and must be an expression.
  • Multiple, implicitly typed variables cannot be initialized in the same statement.
  • You can’t set the initializer to an object unless you create a new object in the initializer.

Default Value Expressions

Default value expressions are especially useful in combination with generic types when you don’t know in advance what the default value for the given type will be.

default(T) Expression: Old Way

A default value expression default(T) returns the default value of a type T, where T is a reference type or a value type.

T variableName = default(T); // syntax

Example:

var name = default(string);
var age = default(int);
var weight = default(int);
var isMarried = default(bool);

// Print Values
Console.WriteLine(name); // null
Console.WriteLine(age); // 0
Console.WriteLine(weight); // 0
Console.WriteLine(isMarried); // False

Run Demo

default literal: New Way

The default literal is a new feature in C# 7.1 that is used to get the default value of the specified data type when the statement is executed. This feature works for value types as well as reference types.

Note: default literal is equivalent to default(T) where T is the inferred type.

string name = default;
int age = default;
int weight = default;
bool isMarried = default;

// Print Values
Console.WriteLine(name); // null
Console.WriteLine(age); // 0
Console.WriteLine(weight); // 0
Console.WriteLine(isMarried); // False

Run Demo

In the output below, a null value is printed as a blank line.

OUTPUT for default literal & default(T)

0
0
False

new Operator

Using the new operator invokes the default constructor of a value type. This allows you to create a variable using the new keyword, which automatically sets the variable to its default value.

Note: All values in C# are an instance of a specific type.

var age = new int(); // 0;
var isMarried = new bool(); // false;

Console.WriteLine(age);
Console.WriteLine(isMarried);

Run Demo

OUTPUT

0
False

The following table shows the default value for the different pre-defined data types.

Type Default Value
sbyte, byte, short, ushort, int, uint, long, ulong 0
char ‘\0’
float 0.0f
double 0.0d
decimal 0.0m
bool False
object null
string null

Types and Variables

There are two kinds of types in C#: value types and reference types.

Variables of value types directly contain their data, whereas variables of reference types store references to their data, the latter being known as objects.

With reference types, it is possible for two variables to reference the same object and, therefore, possible for operations on one variable to affect the object referenced by the other variable. With value types, the variables each have their own copy of the data, and it is not possible for operations on one to affect the other (except in the case of ref and out parameter variables).

Terms Used

camelCase
First letter of the first word is lowercase, while the first letter of every subsequent word is uppercase.
Example: firstName, lastName, fullName, isValid.

Identifier
Identifiers are names used to determine classes, functions, variables, or any item defined by the programmer.

C# Local variables
Local variables are declared inside methods and they only exist during the call to that method. Once the method returns, the memory allocated to any local variables is released.

Declaration
A declaration statement declares a new variable and ends with a semicolon.

Type inference
The compiler determines and assigns the most appropriate type.

C# Reference | Microsoft Docs


Tagged in :