Module 1 Csharp
Module 1 Csharp
What is C#?
C# is pronounced "C-Sharp".
It is a modern, general-purpose, object-oriented programming language developed by Microsoft and
approved by European Computer Manufacturers Association (ECMA) and International Standards
Organization (ISO), created by Microsoft that runs on the .NET Framework.
C# has roots from the C family, and the language is close to other popular languages like C++ and Java.
The first version was released in year 2002. The latest version, C# 11, was released in November 2022.
C# is C# was developed by Anders Hejlsberg and his team during the development of .Net Framework.
C# is designed for Common Language Infrastructure (CLI), which consists of the executable code and
runtime environment that allows use of various high-level languages on different computer platforms and
architectures.
The following reasons make C# a widely used professional language −
It is a modern, general-purpose programming language
It is object oriented.
It is component oriented.
It is easy to learn.
It is a structured language.
It produces efficient programs.
It can be compiled on a variety of computer platforms.
It is a part of .Net Framework.
Although C# constructs closely follow traditional high-level languages, C and C++ and being an object-
oriented programming language. It has strong resemblance with Java, it has numerous strong programming
features that make it endearing to a number of programmers worldwide.
Following is the list of few important features of C# −
Boolean Conditions
Automatic Garbage Collection
Standard Library
Assembly Versioning
Properties and Events
Delegates and Events Management
Easy-to-use Generics
Indexers
Conditional Compilation
Simple Multithreading
LINQ and Lambda Expressions
Integration with Windows
C# is used for:
Mobile applications
Desktop applications
Web applications
Web services
Web sites
Games
VR
Database applications
Why Use C#?
Windows applications
Web applications
Web services
The .Net framework applications are multi-platform applications. The framework has been designed in
such a way that it can be used from any of the following languages: C#, C++, Visual Basic, Jscript,
COBOL, etc. All these languages can access the framework as well as communicate with each other.
The .Net framework consists of an enormous library of codes used by the client languages such as C#.
Following are some of the components of the .Net framework −
Integer Literals: A literal of integer type is known as the integer literal. It can be octal,
decimal, binary, or hexadecimal constant. No prefix is required for the decimal numbers. A
suffix can also be used with the integer literals like U or u are used for unsigned numbers
while l or L are used for long numbers. By default, every literal is of int type. For Integral data
types (byte, short, int, long), we can specify literals in the ways:
Decimal literals (Base 10): In this form, the allowed digits are 0-9.
int x = 101;
Octal literals (Base 8): In this form, the allowed digits are 0-7.
// The octal number should be prefix with 0.
int x = 0146;
Hexa-decimal literals (Base 16): In this form, the allowed digits are 0-9 and characters are a-f.
We can use both uppercase and lowercase characters. As we know that c# is a case-sensitive
programming language but here c# is not case-sensitive.
// The hexa-decimal number should be prefix
// with 0X or 0x.
int x = 0X123Face;
Binary literals (Base 2): In this form, the allowed digits are only 1’s and 0’s.
// The binary number should be prefix with 0b.
int x = 0b101
// C# program to illustrate the use of Integer Literals
using System;
class Example{
// Main method
public static void Main(String[] args)
{
// decimal-form literal
int a = 101;
// octal-form literal
int b = 0145;
// Hexa-decimal form literal
int c = 0xFace;
// binary-form literal
int x = 0b101;
Console.WriteLine(a);
Console.WriteLine(b);
Console.WriteLine(c);
Console.WriteLine(x);
}
}
Output:
101
145
64206
5
Floating-point Literals: The literal which has an integer part, a decimal point, a fractional part, and an
exponent part is known as the floating-point literal. These can be represented either in decimal form or
exponential form.
Examples:
class Example{
// Main Method
public static void Main(String[] args)
{
// decimal-form literal
double a = 101.230;
// It also acts as decimal literal
double b = 0123.222;
Console.WriteLine(a);
Console.WriteLine(b);
}
}
Output:
101.23
123.222
Note: By default, every floating-point literal is of double type and hence we can’t assign directly to float
variable. But we can specify floating-point literal as float type by suffixed with f or F. We can specify
explicitly floating-point literal as the double type by suffixed with d or D, of course, this convention is
not required.
Character Literals: For character data types we can specify literals in 3 ways:
Single quote:
We can specify literal to char data type as single character within single quote.
char ch = 'a';
Unicode Representation:
We can specify char literals in Unicode representation ‘\uxxxx’. Here xxxx represents 4 hexadecimal
numbers.
char ch = '\u0061';// Here /u0061 represent a.
Escape Sequence:
Every escape character can be specified as char literals.
char ch = '\n';
Example :
Output :
a
a
Hello
Geeks !
String Literals: Literals which are enclosed in double quotes(“”) or starts with @”” are known as the
String literals.
Examples:
String s1 = "Hello Geeks!";
String s2 = @"Hello Geeks!";
Program:
// C# program to illustrate the use of String literals
using System;
class Example{
// Main Method
public static void Main(String[] args)
{
String s = "Hello Geeks!";
String s2 = @"Hello Geeks!";
// If we assign without "" then it treats as a variable and causes compiler error
// String s1 = Geeks;
Console.WriteLine(s);
Console.WriteLine(s2);
}
}
Output:
Hello Geeks!
Hello Geeks!
Boolean Literals: Only two values are allowed for Boolean literals i.e. true and false.
Example:
bool b = true;
bool c = false;
Program:
// C# program to illustrate the use of boolean literals
using System;
class Example{
// Main Method
public static void Main(String[] args)
{
bool b = true;
bool c = false;
// these will give compile time error
// bool d = 0;
// bool e = 1;
// Console.WriteLine(d);
// Console.WriteLine(e);
Console.WriteLine(b);
Console.WriteLine(c);
}
}
Output:
True
False
C# Variables
A typical program uses various values that may change during its execution. For example, a program
that performs some operations on the values entered by the user.
The values entered by one user may differ from those entered by another user. Hence this makes it
necessary to use variables as another user may not use the same values.
When a user enters a new value that will be used in the process of operation, can store temporarily in the
Random Access Memory of computer and these values in this part of memory vary throughout the
execution and hence another term for this came which is known as Variables.
So basically, a Variable is a placeholder of the information which can be changed at runtime. And
variables allows to Retrieve and Manipulate the stored information.
Syntax:
Example:
char var = 'h'; // Declaring and Initializing character variable
int a, b, c; // Declaring variables a, b and c of int type
Characteristics of Variables:
Example :
int folks;
float interest;
Initializing Variables
The term initializing means to assign some value to the variable. Basically, the actual use of variables
comes under the initialization part. In C# each data type has some default value which is used when
there is no explicitly set value for a given variable. Initialization can be done separately or may be with
declaration.
Example :
Example :
Value of x is 32
Value of y is 0
2. Run Time Initialization
In this, the user has to enter the value and that value is copied to the required variable. In this type of
initialization, there is one more possibility in which value is assigned to variable after completion of a
function call.
Example:
Input : 45
Output : Value of num is 45
Input : 27
Output : Value of num is 27
Note: Here the Console.ReadLine() method asks the user to enter the value and later on it puts the same
value in the “num” variable. Hence the value will be displayed according to the user input.
Data types specify the type of data that a valid C# variable can hold. C# is a strongly typed
programming language because in C#, each type of data (such as integer, character, float, and so forth) is
predefined as part of the programming language and all constants or variables defined for a given
program must be described with one of the data types.
C# Data types
Value Data Types : In C#, the Value Data Types will directly store the variable value in memory and it
will also accept both signed and unsigned literals. The derived class for these data types are
System.ValueType.
Floating Point Types: There are 2 floating point data types which contain the decimal point.
Float: It is 32-bit single-precision floating point type. It has 7 digit Precision. To initialize a float
variable, use the suffix f or F. Like, float x = 3.5F;. If the suffix F or f will not use then it is treated as
double.
Double:It is 64-bit double-precision floating point type. It has 14 – 15 digit Precision. To initialize a
double variable, use the suffix d or D. But it is not mandatory to use suffix because by default floating
data types are the double type.
Decimal Types : The decimal type is a 128-bit data type suitable for financial and monetary calculations.
It has 28-29 digit Precision. To initialize a decimal variable, use the suffix m or M. Like as, decimal x =
300.5m;. If the suffix m or M will not use then it is treated as double.
Character Types : The character types represents a UTF-16 code unit or represents the 16-bit Unicode
character.
Example :
// C# program to demonstrate the above data types
using System;
namespace ValueTypeTest {
class Example {
// Main function
static void Main()
{
// declaring character
char a = 'G';
// Integer data type is generally
// used for numeric values
int i = 89;
short s = 56;
// this will give error as number is larger than short range
// short s1 = 87878787878;
// long uses Integer values which may signed or unsigned
long l = 4564;
// UInt data type is generally used for unsigned integer values
uint ui = 95;
ushort us = 76;
// this will give error as number is larger than short range
// ulong data type is generally used for unsigned integer values
ulong ul = 3624573;
// by default fraction value is double in C#
double d = 8.358674532;
// for float use 'f' as suffix
float f = 3.7330645f;
// for float use 'm' as suffix
decimal dec = 389.5m;
Console.WriteLine("char: " + a);
Console.WriteLine("integer: " + i);
Console.WriteLine("short: " + s);
Console.WriteLine("long: " + l);
Console.WriteLine("float: " + f);
Console.WriteLine("double: " + d);
Console.WriteLine("decimal: " + dec);
Console.WriteLine("Unsinged integer: " + ui);
Console.WriteLine("Unsinged short: " + us);
Console.WriteLine("Unsinged long: " + ul);
}
}
}
Output :
char: G
integer: 89
short: 56
long: 4564
float: 3.733064
double: 8.358674532
decimal: 389.5
Unsinged integer: 95
Unsinged short: 76
Unsinged long: 3624573
Pointer Data Type : The Pointer Data Types will contain a memory address of the variable value.
To get the pointer details we have a two symbols ampersand (&) and asterisk (*).
ampersand (&): It is Known as Address Operator. It is used to determine the address of a variable.
asterisk (*): It also known as Indirection Operator. It is used to access the value of an address.
Syntax :
type* identifier;
Example :
C# OPERATORS
Operators are the foundation of any programming language. Thus the functionality of C# language is
incomplete without the use of operators. Operators allow us to perform different kinds of operations on
operands. In C#, operators Can be categorized based upon their different functionality :
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Conditional Operator
Arithmetic Operators
Addition: The ‘+’ operator adds two operands. For example, x+y.
Subtraction: The ‘-‘ operator subtracts two operands. For example, x-y.
Multiplication: The ‘*’ operator multiplies two operands. For example, x*y.
Division: The ‘/’ operator divides the first operand by the second.
Modulus: The ‘%’ operator returns the remainder when first operand is divided by the second.
For example, x%y.
Example:
// C# program to demonstrate the working of Binary Arithmetic Operators
using System;
namespace Arithmetic
{
class GFG
{
// Main Function
static void Main(string[] args)
{
int result;
int x = 10, y = 5;
// Addition
result = (x + y);
Console.WriteLine("Addition Operator: " + result);
// Subtraction
result = (x - y);
Console.WriteLine("Subtraction Operator: " + result);
// Multiplication
result = (x * y);
Console.WriteLine("Multiplication Operator: "+ result);
// Division
result = (x / y);
Console.WriteLine("Division Operator: " + result);
// Modulo
result = (x % y);
Console.WriteLine("Modulo Operator: " + result);
}
}
}
Output:
Addition Operator: 15
Subtraction Operator: 5
Multiplication Operator: 50
Division Operator: 2
Modulo Operator: 0
Increment: The ‘++’ operator is used to increment the value of an integer. When placed before
the variable name (also called pre-increment operator), its value is incremented instantly. For
example, ++x.
And when it is placed after the variable name (also called post-increment operator), its value is
preserved temporarily until the execution of this statement and it gets updated before the
execution of the next statement. For example, x++.
Decrement: The ‘- -‘ operator is used to decrement the value of an integer. When placed before
the variable name (also called pre-decrement operator), its value is decremented instantly. For
example, – -x.
And when it is placed after the variable name (also called post-decrement operator), its value is
preserved temporarily until the execution of this statement and it gets updated before the
execution of the next statement. For example, x--.
Example:
// C# program to demonstrate the working of Unary Arithmetic Operators
using System;
namespace Arithmetic {
class GFG {
// Main Function
static void Main(string[] args)
{
int a = 10, res;
// post-increment example:
// res is assigned 10 only,
// a is not updated yet
res = a++;
//a becomes 11 now
Console.WriteLine("a is {0} and res is {1}", a, res);
// post-decrement example:
// res is assigned 11 only, a is not updated yet
res = a--;
//a becomes 10 now
Console.WriteLine("a is {0} and res is {1}", a, res);
// pre-increment example:
// res is assigned 11 now since a
// is updated here itself
res = ++a;
// a and res have same values = 11
Console.WriteLine("a is {0} and res is {1}", a, res);
// pre-decrement example:
// res is assigned 10 only since
// a is updated here itself
res = --a;
// a and res have same values = 10
Console.WriteLine("a is {0} and res is {1}",a, res);
}
}
}
Output:
a is 11 and res is 10
a is 10 and res is 11
a is 11 and res is 11
a is 10 and res is 10
Relational Operators
Relational operators are used for comparison of two values. Let’s see them one by one:
‘=='(Equal To) operator checks whether the two given operands are equal or not. If so, it returns
true. Otherwise it returns false. For example, 5==5 will return true.
‘!='(Not Equal To) operator checks whether the two given operands are equal or not. If not, it
returns true. Otherwise it returns false. It is the exact boolean complement of the ‘==’ operator.
For example, 5!=5 will return false.
‘>'(Greater Than) operator checks whether the first operand is greater than the second operand.
If so, it returns true. Otherwise it returns false. For example, 6>5 will return true.
‘<‘(Less Than) operator checks whether the first operand is lesser than the second operand. If
so, it returns true. Otherwise it returns false. For example, 6<5 will return false.
‘>='(Greater Than Equal To) operator checks whether the first operand is greater than or equal
to the second operand. If so, it returns true. Otherwise it returns false. For example, 5>=5 will
return true.
‘<='(Less Than Equal To) operator checks whether the first operand is lesser than or equal to the
second operand. If so, it returns true. Otherwise it returns false. For example, 5<=5 will also
return true.
Example:
// C# program to demonstrate the working of Relational Operators
using System;
namespace Relational {
class GFG {
// Main Function
static void Main(string[] args)
{ bool result;
int x = 5, y = 10;
// Equal to Operator
result = (x == y);
Console.WriteLine("Equal to Operator: " + result);
// Greater than Operator
result = (x > y);
Console.WriteLine("Greater than Operator: " + result);
Logical AND: The ‘&&’ operator returns true when both the conditions in consideration are
satisfied. Otherwise it returns false. For example, a && b returns true when both a and b are true
(i.e. non-zero).
Logical OR: The ‘||’ operator returns true when one (or both) of the conditions in consideration
is satisfied. Otherwise it returns false. For example, a || b returns true if one of a or b is true (i.e.
non-zero). Of course, it returns true when both a and b are true.
Logical NOT: The ‘!’ operator returns true the condition in consideration is not satisfied.
Otherwise it returns false. For example, !a returns true if a is false, i.e. when a=0.
Example:
// C# program to demonstrate the working of Logical Operators
using System;
namespace Logical {
class GFG {
// Main Function
static void Main(string[] args) {
bool a = true, b = false, result;
// AND operator
result = a && b;
Console.WriteLine("AND Operator: " + result);
// OR operator
result = a || b;
Console.WriteLine("OR Operator: " + result);
// NOT operator
result = !a;
Console.WriteLine("NOT Operator: " + result);
}
}
}
Output:
AND Operator: False
OR Operator: True
NOT Operator: False
Bitwise Operators
In C#, there are 6 bitwise operators which work at bit level or used to perform bit by bit
operations. Following are the bitwise operators :
& (bitwise AND) Takes two numbers as operands and does AND on every bit of two numbers.
The result of AND is 1 only if both bits are 1.
| (bitwise OR) Takes two numbers as operands and does OR on every bit of two numbers. The
result of OR is 1 any of the two bits is 1.
^ (bitwise XOR) Takes two numbers as operands and does XOR on every bit of two numbers.
The result of XOR is 1 if the two bits are different.
<< (left shift) Takes two numbers, left shifts the bits of the first operand, the second operand
decides the number of places to shift.
>> (right shift) Takes two numbers, right shifts the bits of the first operand, the second operand
decides the number of places to shift.
Example:
// C# program to demonstrate the working of Bitwise Operators
using System;
namespace Bitwise {
class GFG {
// Main Function
static void Main(string[] args) {
int x = 5, y = 10, result;
// Bitwise AND Operator
result = x & y;
Console.WriteLine("Bitwise AND: " + result);
// Bitwise OR Operator
result = x | y;
Console.WriteLine("Bitwise OR: " + result);
// Bitwise XOR Operator
result = x ^ y;
Console.WriteLine("Bitwise XOR: " + result);
// Bitwise AND Operator
result = ~x;
Console.WriteLine("Bitwise Complement: " + result);
// Bitwise LEFT SHIFT Operator
result = x << 2;
Console.WriteLine("Bitwise Left Shift: " + result);
// Bitwise RIGHT SHIFT Operator
result = x >> 2;
Console.WriteLine("Bitwise Right Shift: " + result);
}
}
}
Output:
Bitwise AND: 0
Bitwise OR: 15
Bitwise XOR: 15
Bitwise Complement: -6
Bitwise Left Shift: 20
Bitwise Right Shift: 1
Assignment Operators
Assignment operators are used to assigning a value to a variable. The left side operand of the
assignment operator is a variable and right-side operand of the assignment operator is a value.
The value on the right side must be of the same data-type of the variable on the left side
otherwise the compiler will raise an error.
Different types of assignment operators are shown below:
“=”(Simple Assignment): This is the simplest assignment operator. This operator is used to
assign the value on the right to the variable on the left.
Example:
a = 10;
b = 20;
ch = 'y';
“+=”(Add Assignment): This operator is combination of ‘+’ and ‘=’ operators. This operator
first adds the current value of the variable on left to the value on the right and then assigns the
result to the variable on the left.
Example:
(a += b) can be written as (a = a + b)
If initially value stored in a is 5. Then (a += 6) = 11.
“-=”(Subtract Assignment): This operator is combination of ‘-‘ and ‘=’ operators. This operator
first subtracts the current value of the variable on left from the value on the right and then
assigns the result to the variable on the left.
Example:
(a -= b) can be written as (a = a - b)
If initially value stored in a is 8. Then (a -= 6) = 2.
“*=”(Multiply Assignment): This operator is combination of ‘*’ and ‘=’ operators. This
operator first multiplies the current value of the variable on left to the value on the right and
then assigns the result to the variable on the left.
Example:
(a *= b) can be written as (a = a * b)
If initially value stored in a is 5. Then (a *= 6) = 30.
“/=”(Division Assignment): This operator is combination of ‘/’ and ‘=’ operators. This operator
first divides the current value of the variable on left by the value on the right and then assigns
the result to the variable on the left.
Example:
(a /= b) can be written as (a = a / b)
If initially value stored in a is 6. Then (a /= 2) = 3.
“%=”(Modulus Assignment): This operator is combination of ‘%’ and ‘=’ operators. This
operator first modulo the current value of the variable on left by the value on the right and then
assigns the result to the variable on the left.
Example:
(a %= b) can be written as (a = a % b)
If initially value stored in a is 6. Then (a %= 2) = 0.
“<<=”(Left Shift Assignment) : This operator is combination of ‘<<‘ and ‘=’ operators. This
operator first Left shift the current value of the variable on left by the value on the right and then
assigns the result to the variable on the left.
Example:
(a <<= 2) can be written as (a = a << 2)
If initially value stored in a is 6. Then (a <<= 2) = 24.
“>>=”(Right Shift Assignment) : This operator is combination of ‘>>’ and ‘=’ operators. This
operator first Right shift the current value of the variable on left by the value on the right and
then assigns the result to the variable on the left.
Example:
(a >>= 2) can be written as (a = a >> 2)
If initially value stored in a is 6. Then (a >>= 2) = 1.
“&=”(Bitwise AND Assignment): This operator is combination of ‘&’ and ‘=’ operators. This
operator first “Bitwise AND” the current value of the variable on the left by the value on the
right and then assigns the result to the variable on the left.
Example:
(a &= 2) can be written as (a = a & 2)
If initially value stored in a is 6. Then (a &= 2) = 2.
“^=”(Bitwise Exclusive OR): This operator is combination of ‘^’ and ‘=’ operators. This
operator first “Bitwise Exclusive OR” the current value of the variable on left by the value on
the right and then assigns the result to the variable on the left.
Example:
(a ^= 2) can be written as (a = a ^ 2)
If initially value stored in a is 6. Then (a ^= 2) = 4.
“|=”(Bitwise Inclusive OR) : This operator is combination of ‘|’ and ‘=’ operators. This operator
first “Bitwise Inclusive OR” the current value of the variable on left by the value on the right
and then assigns the result to the variable on the left.
Example :
(a |= 2) can be written as (a = a | 2)
If initially, value stored in a is 6. Then (a |= 2) = 6.
Example:
// C# program to demonstrate the working of Assignment Operators
using System;
namespace Assignment {
class GFG {
// Main Function
static void Main(string[] args){
// initialize variable x using Simple Assignment Operator "="
int x = 15;
// it means x = x + 10
x += 10;
Console.WriteLine("Add Assignment Operator: " + x);
// initialize variable x again
x = 20;
// it means x = x - 5
x -= 5;
Console.WriteLine("Subtract Assignment Operator: " + x);
// initialize variable x again
x = 15;
// it means x = x * 5
x *= 5;
Console.WriteLine("Multiply Assignment Operator: " + x);
// initialize variable x again
x = 25;
// it means x = x / 5
x /= 5;
Console.WriteLine("Division Assignment Operator: " + x);
// initialize variable x again
x = 25;
// it means x = x % 5
x %= 5;
Console.WriteLine("Modulo Assignment Operator: " + x);
// initialize variable x again
x = 8;
// it means x = x << 2
x <<= 2;
Console.WriteLine("Left Shift Assignment Operator: " + x);
// initialize variable x again
x = 8;
// it means x = x >> 2
x >>= 2;
Console.WriteLine("Right Shift Assignment Operator: " + x);
// initialize variable x again
x = 12;
// it means x = x >> 4
x &= 4;
Console.WriteLine("Bitwise AND Assignment Operator: " + x);
// initialize variable x again
x = 12;
// it means x = x >> 4
x ^= 4;
Console.WriteLine("Bitwise Exclusive OR Assignment Operator: " + x);
// initialize variable x again
x = 12;
// it means x = x >> 4
x |= 4;
Console.WriteLine("Bitwise Inclusive OR Assignment Operator: " + x);
}
}
}
Output :
Add Assignment Operator: 25
Subtract Assignment Operator: 15
Multiply Assignment Operator: 75
Division Assignment Operator: 5
Modulo Assignment Operator: 0
Left Shift Assignment Operator: 32
Right Shift Assignment Operator: 2
Bitwise AND Assignment Operator: 4
Bitwise Exclusive OR Assignment Operator: 8
Bitwise Inclusive OR Assignment Operator: 12
Conditional Operator
It is ternary operator which is a shorthand version of if-else statement. It has three operands and
hence the name ternary. It will return one of two values depending on the value of a Boolean
expression.
Syntax:
condition ? first_expression : second_expression;
Explanation:
condition: It must be evaluated to true or false.
If the condition is true
first_expression is evaluated and becomes the result.
If the condition is false,
second_expression is evaluated and becomes the result.
Example:
// C# program to demonstrate the working of Conditional Operator
using System;
namespace Conditional {
class GFG {
// Main Function
static void Main(string[] args)
{
int x = 5, y = 10, result;
// To find which value is greater Using Conditional Operator
result = x > y ? x : y;
// To display the result
Console.WriteLine("Result: " + result);
// To find which value is greater using Conditional Operator
result = x < y ? x : y;
// To display the result
Console.WriteLine("Result: " + result);
}
}
}
Output :
Result: 10
Result: 5
C# provides checked and unchecked keyword to handle integral type exceptions. Checked and
unchecked keywords specify checked context and unchecked context respectively. In checked
context, arithmetic overflow raises an exception whereas, in an unchecked context, arithmetic
overflow is ignored and result is truncated.
C# Checked
The checked keyword is used to explicitly check overflow and conversion of integral type
values at compile time.Let's first see an example that does not use checked keyword.
C# Checked Example without using checked
using System;
namespace CSharpProgram {
class Program {
static void Main(string[] args) {
int val = int.MaxValue;
Console.WriteLine(val + 2);
}
}
}
Output :
-2147483647
See, the above program produces the wrong result and does not throw any overflow exception.
using System;
namespace CSharpProgram {
class Program {
checked
Console.WriteLine(val + 2);
}
}
Output:
C# Unchecked
The Unchecked keyword ignores the integral type arithmetic exceptions. It does not check
explicitly and produce result that may be truncated or wrong.
Example
using System;
namespace CSharpProgram {
class Program {
unchecked
Console.WriteLine(val + 2);
Output:
-2147483647
C# Expressions
double temperature;
temperature = 42.05;
Here, 42.05 is an expression. Also, temperature = 42.05 is an expression too.
int a, b, c, sum;
sum = a + b + c;
Here, a + b + c is an expression.
Console.WriteLine("Eligible to work");
Here, (age>=18 && age<58) is an expression that returns a boolean value. "Eligible to work" is
also an expression.
In C#, a constant holds a value that is known at compile time and does not change during the
execution of the program.
To define a constant, you use the const keyword with the following syntax:
C# only allows you to use built-in types except for the object as constants.
If you define constants inside a method, the constants are only accessible within the method.
However, if you define constants in a class, you can use the access modifiers such as public and
private to control the accessibility level of the constants.
C# constants examples
The following example defines a Converter class with the KgToPound() method that converts
weight from kilogram to pound:
// Converter.cs
class Converter
In this KgToPound() method, we define the factor constant with the value 2.205. Because the
factor is local to the KgToPound() method, you can only use it inside the method. In other
words, you cannot use the factor constant in other methods.
The following example redefines the above Converter class that has the Factor constant defined
as a class member:
// Converter.cs
class Converter
}}
Decision Making in programming is similar to decision making in real life. In programming too,
a certain block of code needs to be executed when some condition is fulfilled.
A programming language uses control statements to control the flow of execution of program
based on certain conditions. These are used to cause the flow of execution to advance and
branch based on changes to the state of a program.
if
if-else
if-else-if
Nested if
Switch
Nested switch
IF Statement
The if statement checks the given condition. If the condition evaluates to be true then the block
of code/statements will execute otherwise not.
Syntax:
if(condition) {
//code to be executed
}
Note: If the curly brackets { } are not used with if statements then the statement just next to it is
only considered associated with the if statement.
Example:
if (condition)
statement 1;
statement 2;
In this example, only statement 1 is considered to be associated with the if statement.
Example:
// C# program to illustrate if statement
using System;
public class ex {
public static void Main(string[] args) {
string name = "hello";
if (name == "hello") {
Console.WriteLine("hello folks!!");
}
} }
IF – else Statement
The if statement evaluates the code if the condition is true but what if the condition is not true,
here comes the else statement. It tells the code what to do when the if condition is false.
Syntax:
if(condition)
{
// code if condition is true
}
else
{
// code if condition is false
}
Example:
// C# program to illustrate if-else statement
using System;
public class Ex {
public static void Main(string[] args)
{
string name = "hai";
if (name == "hai") {
Console.WriteLine("hai folks!!");
}
else {
Console.WriteLine("hello all!!");
}
}
}
Output:
Hai
If – else – if ladder Statement
The if-else-if ladder statement executes one condition from multiple statements. The execution
starts from top and checked for each if condition. The statement of if block will be executed
which evaluates to be true. If none of the if condition evaluates to be true then the last else block
is evaluated.
Syntax:
if(condition1){
// code to be executed if condition1 is true
}
else if(condition2) {
// code to be executed if condition2 is true
}
else if(condition3) {
// code to be executed if condition3 is true
}
...
else {
// code to be executed if all the conditions are false
}
Example:
using System;
class Ex {
}}
Output:
i is 20
Nested – If Statement
if statement inside an if statement is known as nested if. if statement in this case is the target of
another if or else statement. When more than one condition needs to be true and one of the
condition is the sub-condition of parent condition, nested if can be used.
Syntax:
if (condition1) {
// code to be executed
// if condition2 is true
if (condition2) {
// code to be executed
// if condition2 is true
} }
Example:
using System;
class EX {
int i = 10;
if (i == 10) {
if (i < 12)
else
}}
Output:
Switch Statement
Switch statement is an alternative to long if-else-if ladders. The expression is checked for
different cases and the one match is executed. break statement is used to move out of the switch.
If the break is not used, the control will flow to all cases below it until break is found or switch
comes to an end. There is default case (optional) at the end of switch, if none of the case
matches then default case is executed.
Syntax:
switch (expression) {
break;
break;
break;
Example:
using System;
class EX {
int i = 10;
if (i == 10) {
if (i < 12)
else
}}
Output:
The data type of the variable in the switch and value of a case must be of the same type.
The value of a case must be a constant or a literal. Variables are not allowed.
The default statement is optional and it can be used anywhere inside the switch statement.
Nested switch
Nested Switch case are allowed in C# . In this case, switch is present inside other switch case.
Inner switch is present in one of the cases in parent switch.
Example:
using System;
int j = 5;
switch (j)
case 5: Console.WriteLine(5);
switch (j - 1) {
case 4: Console.WriteLine(4);
switch (j - 2) {
case 3: Console.WriteLine(3);
break;
break;
}
break;
break;
break;
default: Console.WriteLine(100);
break;
Output:
3
Loops in C#
2. for loop for loop has similar functionality as while loop but with different syntax. for loops
are preferred when the number of times loop statements are to be executed is known
beforehand. The loop variable initialization, condition to be tested, and increment/decrement of
the loop variable is done in one line in for loop thereby providing a shorter, easy to debug
structure of looping.
Syntax:
// statements to be executed
1. Initialization of loop variable: Th expression / variable controlling the loop is initialized here.
It is the starting point of for loop. An already declared variable can be used or a variable can be
declared, local to loop only.
2. Testing Condition: The testing condition to execute statements of loop. It is used for testing
the exit condition for a loop. It must return a boolean value true or false. When the condition
became false the control will be out from the loop and for loop ends.
Example:
using System;
class forLoopDemo{
}}
Output:
hai all
hai all
hai all
hai all
Exit Controlled Loops: The loops in which the testing condition is present at the end of loop
body are termed as Exit Controlled Loops. do-while is an exit controlled loop.
Note: In Exit Controlled Loops, loop body will be evaluated for at-least one time as the testing
condition is present at the end of loop body.
1. do-while loop do while loop is similar to while loop with the only difference that it checks
the condition after executing the statements, i.e it will execute the loop body one time for sure
because it checks the condition after executing the statements.
Syntax:
do{
statements..
} while (condition);
Example :
using System;
class dowhileloopDemo{
int x = 21;
do
Console.WriteLine(“hello people");
x++;
Output:
hello people
Infinite Loops: The loops in which the test condition does not evaluate false ever tend to
execute statements forever until an external force is used to end it and thus they are known as
infinite loops.
Example:
using System;
class infiniteLoop{
for(;;)
}}
Output:
..........
Nested Loops: When loops are present inside the other loops, it is known as nested loops.
Example:
using System;
class nestedLoops{
Console.WriteLine("hello world");
}}
Output:
hello world
In C#, Jump statements are used to transfer control from one point to another point in the
program due to some specified code while executing the program. There are five keywords in
the Jump Statements:
break
continue
goto
return
throw
break statement
The break statement is used to terminate the loop or statement in which it present. After that, the
control will pass to the statements that present after the break statement, if available. If the
break statement present in the nested loop, then it terminates only those loops which contains
break statement.
Example:
using System;
class ex {
// Main Method
if (i == 3) break;
Console.WriteLine("hello world");
} }
Output:
hello world
continue statement
This statement is used to skip over the execution part of the loop on a certain condition. After
that, it transfers the control to the beginning of the loop. Basically, it skips its following
statements and continues with the next iteration of the loop.
Example:
using System;
// if the value of i becomes 4 then it will skip 4 and send the transfer to the for
//loop and continue with 5
if (i == 4) continue;
Console.WriteLine(i);
} }
Output:
9
10
goto statement
This statement is used to transfer control to the labeled statement in the program. The label is
the valid identifier and placed just before the statement from where the control is transferred.
Example:
using System;
class Ex {
// Main Method
switch (number) {
case 5:
Console.WriteLine("case 5");
break;
case 10:
Console.WriteLine("case 10");
break;
case 20:
Console.WriteLine("case 20");
goto case 5;
default:
} }
Output:
case 20
case 5
return statement
This statement terminates the execution of the method and returns the control to the calling
method. It returns an optional value. If the type of method is void, then the return statement can
be excluded.
Example:
using System;
class ex {
int add = a + a;
return add;
} // Main Method
int number = 2;
} }
Output:
The addition is 4
throw statement
This is used to create an object of any valid exception class with the help of new keyword
manually. The valid exception must be derived from the Exception class.
Example:
using System;
class Ex {
if (sub1 == null)
// Main Method
try {
displaysubject(sub);
catch(Exception exp) {
Console.WriteLine(exp.Message );
} }
Output:
Exception Message
C# | Methods
Methods are generally the block of codes or statements in a program that gives the user the
ability to reuse the same code which ultimately saves the excessive use of memory, acts as a
time saver and more importantly, it provides a better readability of code.
So basically, a method is a collection of statements that perform some specific task and return
the result to the caller. A method can also perform some specific task without returning
anything.
Example :
return area;
}
Method declaration means the way to construct method including its naming.
Syntax :
<Access_Modifier> <return_type> <method_name>([<param_list>])
Modifier : It defines access type of the method i.e. from where it can be accessed in your
application. In C# there are Public, Protected, Private access modifiers.
Name of the Method : It describes the name of the user defined method by which the user
calls it or refer it. Eg. GetName()
Return type: It defines the data type returned by the method. It depends upon user as it may
also return void value i.e return nothing
Body of the Method : It refers to the line of code of tasks to be performed by the method
during its execution. It is enclosed between braces.
Parameter list : Comma separated list of the input parameters are defined, preceded with their
data type, within the enclosed parenthesis. If there are no parameters, then empty parentheses
() have to use out.
There are certain pre-defined rules for naming methods which a user should follow :
The first letter of the method name can be either a small letter or a Capital letter, however, it
is recommended to use the capital one.
These rules are not mandatory, but recommendable. Generally, a method has a unique name
within the class in which it is defined but sometime a method might have the same name as
other method names within the same class as method overloading is allowed in C#.
The Method Body : As discussed above the body of the method consists of statements of
code which a user wants to perform. After the method has been declared, it is dependent on
the user whether to define its implementation or not. Not writing any implementation, makes
the method not to perform any task. However, when the user wants to perform certain tasks
using method then it must write the statements for execution in the body of the method. The
below syntax describes the basic structure of the method body :
Syntax :
<return_type> <method_name>(<parameter_list>)
Method Calling
Method Invocation or Method Calling is done when the user wants to execute the method.
The method needs to be called for using its functionality. A method returns to the code that
invoked it when:
Throws an exception
using System;
namespace ConsoleApplication1 {
class ex {
// Here Sum() method asks for two parameters from the user and
{
// there are two local variables 'a' and 'b' where 'a' is assigned the value of parameter
int a = x;
int b = y;
// The local variable calculates the sum of 'a' and 'b' and returns the result
int result = a + b;
return result;
// Main Method
int a = 12;
int b = 23;
// Method Sum() is invoked and the returned value is stored in the local variable say 'c'
// Display Result
} }
Output :
Method Parameters
There might be certain situations the user want to execute a method but sometimes that
method requires some value inputs in order to execute and complete its tasks.
These input values are known as Parameters in a computer language terms. Now, these
parameters can be either int, long or float or double or char. However, it depends upon the
user requirements. The methods in C# can be classified into different categories based on
return type as well as input parameters.
using System;
namespace ConsoleApplication2 {
class ex{
// Here the method 'PrintSentence()' neither takes any parameter nor returns any value.
//It simply performs the required operations and prints the result within it.
// Main Method
PrintSentence();
} }
Output :
// C# program to illustrate the method Without Parameters & With Return Value Type
using System;
namespace ConsoleApplication3 {
class ex {
add = a + b;
return add;
// Main Method
Console.WriteLine(getresult);
} }
Output :
148
// C# program to illustrate Method With Parameters & Without Return Value Type
using System;
namespace ConsoleApplication3 {
class ex {
// This method take the side of the square as a parameter and after obtaining the result,
// Main Method
// side of square
int p = 5;
// Method invoking
perimeter(p);
} }
Output :
using System;
namespace ConsoleApplication4 {
class ex {
// This method asks a number from the user and using that it calculates the factorial
int f = 1;
f = f * i;
return f;
// Main Method
int p = 4;
}}
Output:
Factorial is: 24
There are many advantages of using methods. Some of them are listed below:
It provides an effective way for the user to reuse the existing code.
It optimizes the execution time and memory space.
C# | Method Overloading
obj.Identity("Akku", 1);
obj.Identity(2, "Abby");
} }
Output:
Name1 : Akku, Id1 : 1
Name2 : Abby, Id2 : 2
C# | Method Overriding
Method Overriding in C# is similar to the virtual function in C++ . Method Overriding is a
technique that allows the invoking of functions from another class (base class) in the derived
class. Creating a method in the derived class with the same signature as a method in the base
class is called as method overriding.
In simple words, Overriding is a feature that allows a subclass or child class to provide a
specific implementation of a method that is already provided by one of its super-classes or
parent classes. When a method in a subclass has the same name, same parameters or
signature and same return type(or sub-type) as a method in its super-class, then the method in
the subclass is said to override the method in the super-class. Method overriding is one of the
ways by which C# achieve Run Time Polymorphism(Dynamic Polymorphism).
The method that is overridden by an override declaration is called the overridden base
method. An override method is a new implementation of a member that is inherited from a
base class. The overridden base method must be virtual, abstract, or override.
Example :
class base_class {
class Main_Method {
d.ex();
} }
Here the base class is inherited in the derived class and the method gfg() which has the same
signature in both the classes, is overridden.
virtual keyword: This modifier or keyword use within base class method. It is used to
modify a method in base class for overridden that particular method in the derived class.
override: This modifier or keyword use with derived class method. It is used to modify a
virtual or abstract method into derived class which presents in base class.
class base_class {
public virtual void ex();
class Main_Method {
d.ex();
b.ex();
} }
Here first, d refers to the object of the class derived_class and it invokes ex() of the class
derived_class then, b refers to the reference of the class base and it hold the object of class
derived and it invokes ex() of the class derived. Here ex() method takes permission from base
class to overriding the method in derived class.
Note: Method overriding is possible only in derived classes. Because a method is overridden
in the derived class from the base class.
C# | Type Casting
Type conversion happens when we assign the value of one data type to another. If the data
types are compatible, then C# does Automatic Type Conversion. If not comparable, then they
need to be converted explicitly which is known as Explicit Type conversion. For example,
assigning an int value to a long variable.
It happens when:
float double
Example :
using System;
namespace Casting {
class ex {
// Main Method
float f = l;
} }
Output:
Int value 57
Long value 57
Float value 57
using System;
namespace Casting{
class ex{
// Main Method
double d = 765.12;
int i = d;
// Display Result
} }
Error :
So, if we want to assign a value of larger data type to a smaller data type we perform explicit
type casting.
This is useful for incompatible data types where automatic conversion cannot be done.
Here, target-type specifies the desired type to convert the specified value to.
Example :
using System;
namespace Casting{
class ex {
// Main Method
public static void Main(String []args) {
double d = 765.12;
int i = (int)d;
// Display Result
} }
Output:
Value of i is 765