C# Tutorial : Lesson 02 – Variables & Operators

Partho Sarathi

25 Apr, 2009 · 9 minutes read

  • Share:
Variables

A Variable is a named location that stores a value. Although variables are physically stored in the RAM, their actual memory address is not known to the programmer. We can use the variables via the name we give them. These are the rules for naming a variable:-

  • The name must begin with a letter or an underscore & can be followed by a sequence of letters (A-Z), digits (0-9) or underscore (_)
  • Special Characters such as ? – * / \ ! @ # $ % ^ ( ) [ ] { } , ; : . cannot be used in the variable name.
  • A variable name must not be the same as a reserved keyword such as using, public, etc.
  • The name can contain any number of the allowed characters
  • Variables with the same scope cannot have the same name

Note: C# being a case-sensitive language, two variables such as var1 and Var1 would be different.

Any Variable has a type associated with it, which basically restricts the type of value it can store. The table below shows the Data types available in C#, the size they occupy in the memory and the values they can contain.

TypeSizeRange of values
char20 and 65536
int4-2,147,483,648 and 2,147,483,647
float4-3.402823E+38 and -1.401298E-45 (For Negative Values)
1.401298E-45 and 3.402823E+38 (For Positive values Values)
double8-1.79769313486232E308 and 4.94065645841247E-324 (For Negative Values)
4.94065645841247E-324 and 1.79769313486232E308 (For Positive values Values)
bool1true or false
stringDepends on length of the string0-2 million Unicode Characters

Variable Declaration

Before we can use a variable, we need to declare it. Declaration of variables are done using the syntax:-
;

For Example:-

int Age;
char Sex;
string Name;
bool IsMarried;

Variables of the same data type can also be declared using the syntax:-
, , .. and so on;

Example:-

int Age, RollNum;
Initialization

While declaring a variable, it is possible to assign an initial value to it. This operation is called Initialization and it has the following syntax:-
= ;

Example:-

int Age = 20;
char Sex = 'M';
string Name = 'Max Steel';
bool IsMarried = false;

Multiple variables of the same data type can also be initialized in a single line of code using the syntax:-
= , = ;

int Age = 20, RollNum = 69;
Value Types

Values can be stored in variables by two methods which are: by value and by reference. Value types store the supplied value directly in the memory whereas reference types store a reference to the memory where the actual value is located. The benefit of the reference type is that changes made to any alias of the variable will reflect across all of its aliases.

Accepting Values in Variables

To input values from the user at runtime, we use the Console.ReadLine()function. For Example:- string FirstName = Console.ReadLine();The above statement would declare a string variable FirstName and store the value retrieved from the user in it.

Note: Console.ReadLine()returns value as a string. Therefore, one must use type casting to convert the value to the required type. We use the member functions of the Convertclass to do this. For Example: int Age = Convert.ToInt32(Console.ReadLine());. Similarly, there are other functions such as ToChar(), ToString, etc for conversion to other data types.

Operators

Similar to mathematics, every programming language has its own set of operators, be it arithmetic or logical. Operators enable us to perform operations on 1 or more values (operands) and calculate the result.

Usage

Depending on the number of operands they take, operators can be either unary or binary.
The use of an operator takes one of the following form:-

Unary Usage


  • Example: ++A;

  • Example: A++;

Binary Usage


  • Example: A + B;
Classification

The operators in C# can be classified as follows:-

Arithmetic operators– Just what the name suggests, these operators are used to perform arithmetic operations.

OperatorUsageUtilityType
+A + BAdd two numbersBinary
A – BSubtract a number from anotherBinary
*A * BMultiply two numbersBinary
/A / BDivide a number with anotherBinary
%A % BRemainder of the operation A / BBinary

Arithmetic Assignment Operators– These can be considered as shortcuts as they are used to perform both arithmetic and assignment operations in a single step.

OperatorUsageUtilityType
=A = 69Store the value 69 into ABinary
+=A += BEquivalent to A = A + BBinary
-=A -= BEquivalent to A = A – BBinary
*=A *= BEquivalent to A = A * BBinary
/=A /= BEquivalent to A = A / BBinary
%=A %= BEquivalent to A = A % BBinary

Increment / Decrement Operators– These operators are used to increment or decrement the value of an operand by 1.

OperatorUsageUtilityType
++++A or A++

Increments the value of A by 1

Unary
--
--A or A--
Decrements the value of A by 1Unary

Difference between Pre & Post Increment/Decrement
Consider the following code snippet:-

int A = 0;
int B = A++;
int C = ++A;

At the very first line, we have used the Arithmetic Assignment operator, =to assign the value of 0 to A. In the proceeding lines we have used both Pre & Post increment. At line 2 int B = A++;the operation being post increment, the value of A i.e 0 is assigned to B followed by the increment of A’s value. At line 3 int C = ++A;the current value of A, i.e. 1 is incremented by 1 following which the new value of A is assigned to C. Therefore, the value of A = 2, B = 0 and C = 2.

What will be the output of the following code?

int A = 5;
int B = (A++) + (--A);
Console.WriteLine("Value of B = {0}", B);

At line, 1, A gets initialized to 5. The next line is a bit tricky. Here, The RHS should be evaluated like 5 + 4 because A++ is post increment and this operation should occur after the line of statement. But, this is not the case, instead it takes place in the same line but after the evaluation of the sub-expression (A++). Hence, the expression will be evaluated as 5 + 5 and the output will be 10.

Comparison Operators– These operators are to compare two values and return the result as either ‘true’or ‘false’.

OperatorUsageUtilityType
<A < B

Compares if A is less than B

Binary
>A > BCompares if B is less than ABinary
<=A <= BCompares if A is less than or equal to BBinary
>=A >= BCompares if A is greater than or equal to BBinary
==A == BCompares if A is equal to BBinary
!=A != BCompares if A is not equal to BBinary

Logical Operators– These operators are used to perform logical operations and return the result as either ‘true’or ‘false’.

OperatorUsageUtilityType
&&A && B

Returns true if Both A and B are true

Binary
||A || BReturn true if either A or B are trueBinary
!!AReturns True if A is falseUnary
^A ^ BReturns true when A and B do not match i.e one is true and the other is falseBinary

Displaying Variables

We us the WriteLine method to display the value stored in variables.

Displaying Single Variable

int A = 6;
Console.WriteLine(A);

Displaying Multiple Variables

int A = 6, B = 9;
Console.WriteLine("{0},{1}", A, B);

Notice the code “{0},{1}”. This is the format for the output to be generated by WriteLine. Since, we are displaying two variables, we need to specify the format accordingly. Here {0} and {1} represent where the proceeding variables A & B will be displayed. Now take a look at the following code snippet:-

int A = 6, B = 9;
Console.WriteLine("The value of A = {0} and B = {1}", A, B);

The output of these lines would be: The value of A = 6 and B = 9. As you can see, the {0} and {1} are replaced by the variables A and B. 0and 1correspond to the index of the variables following the format, starting from 0.

Comments

Software applications are made by a group of coders. Each one of them handles various aspects of the application. Its important to write descriptive texts in order to help other coders understand, the mechanism of the codes you have written. We use comments denoted by // or /* and */ for this very purpose. Example usage:-

// This is a comment
/* These are two lines
of comments */

Note: The compiler ignores all comment entries. // is used for single line of comment while /* and */ are used for multiple lines.

What’s in a Semicolon?

Whitespace except when used inside quotes, is ignored in C#. All statements in C# are terminated by using the semicolon. This allow spanning of codes across multiple lines.

The following lines of code are functionally equivalent.

int A = 6, B = 9; Console.WriteLine("A   B = {0}", A   B); Console.ReadLine();
int A = 6, B = 9;
Console.WriteLine("The sum of {0} and {1} = {2}", A, B, A   B);
Console.ReadLine();
  • Share:

The cleanest blogging platform


2024 © Maxotek. All rights reserved.