You are on page 1of 10

C# tutorial

C# is a simple, modern, general-purpose, object-oriented programming


language developed by Microsoft.
C# programming is very much based on C and C++ programming languages.

Part-5
Assignment Operator =
Arithmetic Operators like +,-,*,/,%
Comparison Operators like ==, !=,>, >=, <, <=
Conditional Operators like &&, ||
Ternary Operator ?: -
Null Coalescing Operator ??
The bool keyword is an alias of System.Boolean. It is used to declare variables to store
the Boolean values, true and false.
In c# language, ternary operator (?) use to check a conduction, so other name of
ternary operator is conditional operator, which work as a if statement. This
operator compares two values. It produces a third value that depends on the result
of the comparison.
Examples used in the demo
using System;
namespace ConsoleApplication1
{
class Program
{
public static void Main()
{
// Assignment Operator example
// Single = is the assignment operator
int i = 10;
bool b = true;

// For dividing 2 numbers we can use either


// % or / operators
int numerator = 10;
int denominator = 2;

// Arithmentic operator / returns quotient


int quotient = numerator / denominator;
Console.WriteLine("Quotient = {0}", quotient);

// Arithmentic operator % returns remainder


int remainder = numerator % denominator;
Console.WriteLine("Remainder = {0}", remainder);

// To compare if 2 numbers are


// equal use comparison operator ==
int number = 10;
if (number == 10)
{
Console.WriteLine("Number is equal to 10");
}

// To compare if 2 numbers are not


// equal use comparison operator !=
if (number != 5)
{
Console.WriteLine("Number is not equal to 5");
}

// When && operator is used all the conditions must


// be true for the code in the "if" block to be executed
int number1 = 10;
int number2 = 20;

if (number1 == 10 && number2 == 20)


{
Console.WriteLine("Both conditions are true");
}

// When || operator is used the code in the "if" block


// is excuted if any one of the condition is true
number1 = 10;
number2 = 21;

if (number1 == 10 || number2 == 20)


{
Console.WriteLine("Atleast one of the condition is true");
}
}
}
}

The example below is not using the ternary operator. Look at the amount of code we have to write to
check if a number is equal to 10, and then initialise a boolean variable to true or false depending on
whether the number is equal to 10 or not.

using System;
namespace ConsoleApplication1
{
class Program
{
public static void Main()
{
int number = 10;

bool isNumber10;

if (number == 10)
{
isNumber10 = true;
}
else
{
isNumber10 = false;
}

Console.WriteLine("Number == 10 is {0}", isNumber10);


}
}

Ternary operator example : We have rewritten the above program using ternary operator. Notice the
amount of code we have to write is greatly reduced.

using System;
namespace ConsoleApplication1
{
class Program
{
public static void Main()
{
int number = 10;

// Ternary operator example


bool isNumber10 = number == 10 ? true : false;

Console.WriteLine("Number == 10 is {0}", isNumber10);


}
}
}

PART-6
we will discuss
1. Nullable types in C#
2. Null Coalescing Operator ??
The ? operator converts non-nullable types to nullable types
The ?? operator is also known as the null-coalescing operator. It returns the left side operand if
the operand is not null else it returns the right side operand.

In C# types are divided into 2 broad categories.


Value Types - int, float, double, structs, enums etc
Reference Types Interface, Class, delegates, arrays etc
By default value types are non nullable. To make them nullable use ?
int i = 0 (i is non nullable, so "i" cannot be set to null, i = null will generate compiler error)
int? j = 0 (j is nullable int, so j=null is legal)
Nullable types bridge the differences between C# types and Database types

Program without using NULL coalescing operator


using System;
class Program
{
static void Main()
{
int AvailableTickets;
int? TicketsOnSale = null;

if (TicketsOnSale == null)
{
AvailableTickets = 0;
}
else
{
AvailableTickets = (int)TicketsOnSale;
}

Console.WriteLine("Available Tickets={0}", AvailableTickets);


}
}

The above program is re-written using NULL coalescing operator


using System;
class Program
{
static void Main()
{
int AvailableTickets;
int? TicketsOnSale = null;

//Using null coalesce operator ??


AvailableTickets = TicketsOnSale ?? 0;

Console.WriteLine("Available Tickets={0}", AvailableTickets);


}
}

PART_7
Implicit conversion is done by the compiler:
1. When there is no loss of information if the conversion is done
2. If there is no possibility of throwing exceptions during the conversion
Example: Converting an int to a float will not loose any data and no exception will be thrown,
hence an implicit conversion can be done.

Where as when converting a float to an int, we loose the fractional part and also a possibility of
overflow exception. Hence, in this case an explicit conversion is required. For explicit
conversion we can use cast operator or the convert class in c#.

Implicit Conversion Example


using System;
class Program
{
public static void Main()
{
int i = 100;

// float is bigger datatype than int. So, no loss of


// data and exceptions. Hence implicit conversion
float f = i;

Console.WriteLine(f);
}
}

Explicit Conversion Example


using System;
class Program
{
public static void Main()
{
float f = 100.25F;

// Cannot implicitly convert float to int.


// Fractional part will be lost. Float is a
// bigger datatype than int, so there is
// also a possiblity of overflow exception
// int i = f;

// Use explicit conversion using cast () operator


int i = (int)f;

// OR use Convert class


// int i = Convert.ToInt32(f);

Console.WriteLine(i);
}
}

Difference between Parse and TryParse


1. If the number is in a string format you have 2 options - Parse() and TryParse()
2. Parse() method throws an exception if it cannot parse the value, whereas TryParse() returns
a bool indicating whether it succeeded or failed.
3. Use Parse() if you are sure the value will be valid, otherwise use TryParse()

PART-8
we will discuss
1. Arrays
2. Advantages and dis-advantages of arrays

An array is a collection of similar data types.

using System;
class Program
{
public static void Main()
{
// Initialize and assign values in different lines
int[] EvenNumbers = new int[3];
EvenNumbers[0] = 0;
EvenNumbers[1] = 2;
EvenNumbers[2] = 4;

// Initialize and assign values in the same line


int[] OddNumbers = { 1, 3, 5};

Console.WriteLine("Printing EVEN Numbers");

// Retrieve and print even numbers from the array


for (int i = 0; i < EvenNumbers.Length; i++)
{
Console.WriteLine(EvenNumbers[i]);
}

Console.WriteLine("Printing ODD Numbers");

// Retrieve and print odd numbers from the array


for (int i = 0; i < OddNumbers.Length; i++)
{
Console.WriteLine(OddNumbers[i]);
}
}
}

Advantages: Arrays are strongly typed.

Disadvantages: Arrays cannot grow in size once initialized. Have to rely on integral indices to
store or retrieve items from the array.
PART-9

Decision Making
Statement Description

An if statement consists of a boolean expression


if statement
followed by one or more statements.

if...else statement An if statement can be followed by an


optional else statement, which executes when
the boolean expression is false.

nested if statements You can use one if or else if statement inside


another if or else if statement(s).

A switch statement allows a variable to be tested


switch statement
for equality against a list of values.

nested switch You can use one switch statement inside


another switch statement(s).
statements

The ? : Operator:

We have covered conditional operator ? : in previous chapter which can be used


to replace if...else statements. It has the following general form:

Exp1 ? Exp2 : Exp3;

Where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the
colon.

The value of a ? expression is determined as follows: Exp1 is evaluated. If it is


true, then Exp2 is evaluated and becomes the value of the entire ? expression. If
Exp1 is false, then Exp3 is evaluated and its value becomes the value of the
expression.

DIFFERENCE BETWEEN
| -means OR it checks the all condition in if statement
|| -means OR if it find the condition is true then it not check other condition.it faster
than |.
& - if the first condition is false then it checks the all other condition.
&& - if the first condition is false then it not checks the other condition.it is faster
than &.
IF Statement: if break statement is used inside a switch statement, the control will
leave the switch statement.
Goto statement: you can either jump to another switch statement or to a specific
label.
using System;

namespace switch_statement
{
class Program
{
static void Main(string[] args)
{
int userchoice;
int coffeecost = 0;

Start:
Console.WriteLine("Please select the size of coffee 1-Small,2-Medium,3-Large");
userchoice = int.Parse(Console.ReadLine());

switch (userchoice)
{
case 1:
coffeecost += 1;
break;

case 2:
coffeecost += 2;
break;

case 3:
coffeecost += 3;
break;

default:
Console.WriteLine("select the right option");
goto Start;

}
Console.WriteLine("Thank You for shopping with us");
Console.WriteLine("cost of coffee {0}Rs", coffeecost);

Console.WriteLine("enter yes or no for more shopping or exit");


string decision = Console.ReadLine();
switch (decision.ToUpper())
{
case "YES":
goto Start;
case "NO":
break;

}
}
}
}

PART-10

Loop Type Description

It repeats a statement or a group of statements while a


while loop
given condition is true. It tests the condition before
executing the loop body.

It executes a sequence of statements multiple times and


for loop
abbreviates the code that manages the loop variable.

do...while loop It is similar to a while statement, except that it tests the


condition at the end of the loop body

You can use one or more loop inside any another while,
nested loops
for or do..while loop.

Difference between while and Do while


1.While loop checks the condition at the beginning whereas do-while loop checks
the condition at the end of the loop.
2.Do loop is guaranteed to execute at least once ,whereas while loop is not.

While example

using System;

namespace WHILE
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("please enter the number to display even number");
int even = int.Parse(Console.ReadLine());

int i = 0;
while (i <= even)
{
Console.WriteLine(i);
i = i + 2;
}
}
}
}

You might also like