You are on page 1of 51

C# programming

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.

Strong Programming Features of C#

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#?

It is one of the most popular programming language in the world


It is easy to learn and simple to use
It has a huge community support
C# is an object oriented language which gives a clear structure to programs and allows code to be reused,
lowering development costs
As C# is close to C, C++ and Java, it makes it easy for programmers to switch to C# or vice versa.

The .Net Framework


The .Net framework is a revolutionary platform that helps you to write the following types of
applications −

 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 −

 Common Language Runtime (CLR)


 The .Net Framework Class Library
 Common Language Specification
 Common Type System
 Metadata and Assemblies
 Windows Forms
 ASP.Net and ASP.Net AJAX
 ADO.Net
 Windows Workflow Foundation (WF)
 Windows Presentation Foundation
 Windows Communication Foundation (WCF)
 LINQ
For the jobs each of these components perform, please see ASP.Net - Introduction, and for details of
each component, please consult Microsoft's documentation.
Integrated Development Environment (IDE) for C#
Microsoft provides the following development tools for C# programming −

 Visual Studio 2010 (VS)


 Visual C# 2010 Express (VCE)
 Visual Web Developer
The last two are freely available from Microsoft official website. Using these tools, you can write all
kinds of C# programs from simple command-line applications to more complex applications. You can
also write C# source code files using a basic text editor, like Notepad, and compile the code into
assemblies using the command-line compiler, which is again a part of the .NET Framework.
Visual C# Express and Visual Web Developer Express edition are trimmed down versions of Visual
Studio and has the same appearance. They retain most features of Visual Studio. In this tutorial, we have
used Visual C# 2010 Express.
You can download it from Microsoft Visual Studio. It gets installed automatically on your machine.
Note: You need an active internet connection for installing the express edition.
C# literals
The fixed values are called as Literal. Literal is a value that is used by the variables. Values can
be either an integer, float or string, etc. 
// Here 100 is a constant/literal.
int x = 100;
Literals can be of the following types: 
 Integer Literals
 Floating-point Literals
 Character Literals
 String Literals
 Null Literals
 Boolean Literals

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:

Double d = 3.14145 // Valid


Double d = 312569E-5 // Valid
Double d = 125E // invalid: Incomplete exponent
Double d = 784f // valid
Double d = .e45 // invalid: missing integer or fraction
Program:

// C# program to illustrate the use of floating-point literals


using System;

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';

Escape Sequence Meaning


\\ \ character
\’ ‘ character
\? ? character
\b Backspace
\a Alert or Bell
\n New Line
\f Form Feed
\r Carriage Return
\v Vertical Tab
\xhh… Hexadecimal number of one or more digits

Example :

// C# program to illustrate the use of char literals


using System;
class Example {
// Main Method
public static void Main(String[] args)
{
// character literal within single quote
char ch = 'a';
// Unicode representation
char c = '\u0061';
Console.WriteLine(ch);
Console.WriteLine(c);
// Escape character literal
Console.WriteLine("Hello\n\nGeeks\t!");
}
}

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:

type variable_name = value;


or
type variable_names;

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:

name : It must be a valid identifier. In above example, var is a valid identifier.


type : It defines the types of information which is to be stored into the variable. In above example char is
a type.
value : It is the actual data which is to be stored in the variable. In above example ‘h’ is the value.
Rules for Naming Variables
Variable names can contain the letters ‘a-z’ or ’A-Z’ or digits 0-9 as well as the character ‘_’.
The name of the variables cannot be started with a digit.
The name of the variable cannot be any C# keyword say int, float, null, String, etc.
Examples:

Valid Variables Names


int age;
float _studentname;
Invalid Variables Names
int if; // "if" is a keyword

Defining or Declaring a Variable


There are some rules that must be followed while declaring variables :
specify its type (such as int)
specify its name (such as age)
Can provide initial value(such as 17)

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 :

int y = 7; // Declaring and initializing the variable at same time


int x; // Declaring variable x
x = 5; // initializing x with value 5

Two Ways for Initialization:

 Compile time initialization


 Run time initialization

1. Compile Time Initialization


It means to provide the value to the variable during the compilation of the program. If the programmer
didn’t provide any value then the compiler will provide some default value to the variables in some
cases. Generally, this type of initialization helpful when the programmer wants to provide some default
value.

Example :

// C# program to demonstrate the Compile Time Initialization


using System;
class Example {
int y;
// Main Method
public static void Main(String []args)
{
// Compile Time Initialization of variable 'x'
// Assigning value 32 to x
int x = 32;
// printing the value
Console.WriteLine("Value of x is "+x);
// creating object to access
// the variable y
Example gfg = new Example();
// printing the value
Console.WriteLine("Value of y is "+gfg.y);
}
}
Output :

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

// C# program to demonstrate the Run Time Initialization


using System;
class Example {
// Main Method
public static void Main(String []args)
{
// Value will be taken from user
// input and assigned to variable
// num
int num = Convert.ToInt32(Console.ReadLine());
// printing the result
Console.WriteLine("Value of num is " + num);
}
}
Output :
Value of num is 45

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

Data types in C# is mainly divided into three categories

Value Data Types


Reference Data Types
Pointer Data Type

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.

Following are different Value Data Types in C# programming language :


Signed & Unsigned Integral Types : There are 8 integral types which provide support for 8-bit, 16-bit,
32-bit, and 64-bit values in signed or unsigned form.
Alias Type Size(bits) Range Default Value
sbyte signed integer 8 -128 to 127 0
short signed integer 16 -32768 to 32767 0
Int signed integer 32 -231 to 231-1 0
long signed integer 64 -263 to 263-1 0L
byte unsigned integer 8 0 to 255 0
ushort unsigned integer 16 0 to 65535 0
uint unsigned integer 32 0 to 232 0
ulong unsigned integer 64 0 to 263 0

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 :

int* p1, p; // Valid syntax


int *p1, *p; // Invalid
Example :
using System;
namespace Pointerprogram {
class EX {
// Main function
static void Main()
{
unsafe
{
// declare variable
int n = 10;

// store variable n address


// location in pointer variable p
int* p = &n;
Console.WriteLine("Value :{0}", n);
Console.WriteLine("Address :{0}", (int)p);
}
}
}
}

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

In C#, Operators can also categorized based upon Number of Operands:


Unary Operator: Operator that takes one operand to perform the operation.
Binary Operator: Operator that takes two operands to perform the operation.
Ternary Operator: Operator that takes three operands to perform the operation.

Arithmetic Operators

These are used to perform arithmetic/mathematical operations on operands. The  Binary


Operators falling in this category are :

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.

For example, x/y.

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

The ones falling into the category of Unary Operators are:

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);

// Less than Operator


result = (x < y);
Console.WriteLine("Less than Operator: " + result);
// Greater than Equal to Operator
result = (x >= y);
Console.WriteLine("Greater than or Equal to: "+ result);
// Less than Equal to Operator
result = (x <= y);
Console.WriteLine("Lesser than or Equal to: "+ result);
// Not Equal To Operator
result = (x != y);
Console.WriteLine("Not Equal to Operator: " + result);
}
}
}
Output:
Equal to Operator: False
Greater than Operator: False
Less than Operator: True
Greater than or Equal to: False
Lesser than or Equal to: True
Not Equal to Operator: True
Logical Operators
They are used to combine two or more conditions/constraints or to complement the evaluation
of the original condition in consideration. They are described below:

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# Checked and Unchecked

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.

C# Checked Example using checked

This program throws an exception and stops program execution.

using System;

namespace CSharpProgram {

class Program {

static void Main(string[] args) {

checked

int val = int.MaxValue;

Console.WriteLine(val + 2);

}
}

Output:

Unhandled Exception: System.OverflowException: Arithmetic operation resulted in an


overflow.

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 {

static void Main(string[] args) {

unchecked

int val = int.MaxValue;

Console.WriteLine(val + 2);

Output:
-2147483647

C# Expressions

An expression in C# is a combination of operands (variables, literals, method calls) and


operators that can be evaluated to a single value. To be precise, an expression must have at least
one operand but may not have any operator.

Let's look at the example below:

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.

if (age>=18 && age<58)

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.

Introduction to the C# constants

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:

const type ConstantName = value;

Code language: C# (cs)

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

Let’s take some examples of using constants.

1) Using C# constants in a method

The following example defines a Converter class with the KgToPound() method that converts
weight from kilogram to pound:

// Converter.cs

class Converter

public decimal KgToPound(decimal weight) {

const decimal factor = 2.205m;

return weight * factor;


}

Code language: C# (cs)

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.

2) Using C# constants in a class

The following example redefines the above Converter class that has the Factor constant defined
as a class member:

// Converter.cs

class Converter

public const decimal Factor = 2.205m;

public decimal KgToPound(decimal weight) {

return weight * Factor;

public decimal PoundToKg(decimal weight) {

return weight / Factor;

}}

Code language: C# (cs)


In this example, since the Factor constant is public, it can be accessed both from methods of the
Converter class and from outside of the class.
C# Decision Making (if, if-else, if-else-if ladder, nested if, switch, nested switch)

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.

The conditional statements of C#:

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:

// C# program to illustrate if-else-if ladder

using System;

class Ex {

public static void Main(String[] args) {


int i = 20;
if (i == 10)
Console.WriteLine("i is 10");
else if (i == 15)
Console.WriteLine("i is 15");
else if (i == 20)
Console.WriteLine("i is 20");
else
Console.WriteLine("i is not present");

}}

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:

// C# program to illustrate nested-if statement

using System;

class EX {

public static void Main(String[] args) {

int i = 10;

if (i == 10) {

// Nested - if statement Will only be executed if statement above it is true

if (i < 12)

Console.WriteLine("i is smaller than 12 too");

else

Console.WriteLine("i is greater than 15");

}}

Output:

i is smaller than 12 too

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) {

case value1: // statement sequence

break;

case value2: // statement sequence

break;

case valueN: // statement sequence

break;

default: // default statement sequence


}

Example:

// C# program to illustrate nested-if statement

using System;

class EX {

public static void Main(String[] args) {

int i = 10;

if (i == 10) {

// Nested - if statement will only be executed if statement above it is true

if (i < 12)

Console.WriteLine("i is smaller than 12 too");

else

Console.WriteLine("i is greater than 15");

}}
Output:

i is smaller than 12 too

Important points to remember:

 In C#, duplicate case values are not allowed.

 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 break in switch statement is used to terminate the current sequence.

 The default statement is optional and it can be used anywhere inside the switch statement.

 Multiple default statements are not allowed.

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:

// C# example for nested switch case

using System;

public class Ex{

public static void Main(String[] args) {

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;

case 10: Console.WriteLine(10);

break;

case 15: Console.WriteLine(15);

break;

default: Console.WriteLine(100);

break;

Output:

3
Loops in C#

Looping in a programming language is a way to execute a statement or a set of statements


multiple times depending on the result of the condition to be evaluated to execute statements. The
result condition should be true to execute statements within loops.
Loops are mainly divided into two categories:
Entry Controlled Loops: The loops in which condition to be tested is present in beginning of
loop body are known as Entry Controlled Loops. while loop and for loop are entry controlled
loops.
1. while loop The test condition is given in the beginning of the loop and all statements are
executed till the given Boolean condition satisfies when the condition becomes false, the control
will be out from the while loop.
Syntax:
while (boolean condition)
{
loop statements...
}
// C# program to illustrate while loop
using System;
class whileLoopDemo {
public static void Main() {
int x = 1;
// Exit when x becomes greater than 4
while (x <= 4) {
Console.WriteLine("Hello all");
// Increment the value of x for next iteration
x++;
}
}
}

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:

for (loop variable initialization ; testing condition; increment / decrement)

// 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.

3. Increment / Decrement: The loop variable is incremented/decremented according to the


requirement and the control then shifts to the testing condition again. Note: Initialization part is
evaluated only once when the for loop starts.

Example:

// C# program to illustrate for loop.

using System;

class forLoopDemo{

public static void Main() {

// for loop begins when x=1and runs till x <=4

for (int x = 1; x <= 4; x++)


Console.WriteLine("hai all");

}}

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 :

// C# program to illustrate do-while loop

using System;

class dowhileloopDemo{

public static void Main() {

int x = 21;

do

// The line will be printed even if the condition is false

Console.WriteLine(“hello people");

x++;

while (x < 20);


}}

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:

// C# program to demonstrate infinite loop

using System;

class infiniteLoop{

public static void Main() {

// The statement will be printed infinite times

for(;;)

Console.WriteLine("This is printed infinite times");

}}

Output:

This is printed infinite times

This is printed infinite times

This is printed infinite times

This is printed infinite times

This is printed infinite times

This is printed infinite times

This is printed infinite times

..........

Nested Loops: When loops are present inside the other loops, it is known as nested loops.

Example:

// C# program to demonstrate nested loops

using System;

class nestedLoops{

public static void Main() {


// loop within loop printing hello world

for(int i = 2; i < 3; i++)

for(int j = 1; j < i; j++)

Console.WriteLine("hello world");

}}

Output:

hello world

C# | Jump Statements (Break, Continue, Goto, Return and Throw)

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:

// C# program to illustrate the use of break statement

using System;

class ex {

// Main Method

static public void Main() {

// hello world is printed only 2 times because of break statement

for (int i = 1; i < 4; i++) {

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:

// C# program to illustrate the use of continue statement

using System;

class EX { // Main Method

public static void Main() {

// This will skip 4 to print

for (int i = 1; i <= 10; i++) {

// 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:

// C# program to illustrate the use of goto statement

using System;

class Ex {

// Main Method

static public void Main() {

int number = 20;

switch (number) {

case 5:

Console.WriteLine("case 5");

break;

case 10:

Console.WriteLine("case 10");

break;

case 20:

Console.WriteLine("case 20");

// goto statement transfer the control to case 5

goto case 5;

default:

Console.WriteLine("No match found");

} }

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:

// C# program to illustrate the use of return statement

using System;

class ex {

// creating simple addition function

static int Addition(int a) {

// add two value and return the result of addition

int add = a + a;

// using return statement

return add;

} // Main Method

static public void Main() {

int number = 2;

// calling addition function

int result = Addition(number);

Console.WriteLine("The addition is {0}", result);

} }

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:

// C# Program to illustrate the use of throw keyword

using System;
class Ex {

// taking null in the string

static string sub = null;

// method to display subject name

static void displaysubject(string sub1) {

if (sub1 == null)

throw new NullReferenceException("Exception Message");

// Main Method

static void Main(string[] args) {

// using try catch block to handle the Exception

try {

// calling the static method

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 :

// Method Name --> GetCircleArea()


// Return Type ---> double

static double GetCircleArea(double radius) {

const float pi = 3.14F;

double area = pi * radius * radius;

return area;

}
Method declaration means the way to construct method including its naming.  
Syntax :  
<Access_Modifier> <return_type> <method_name>([<param_list>])

In C# a method declaration consists of the following components as follows :

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.

Method Signature : Method Signature is defined by mainly two parameters(number of


parameters, type of the parameters and order of the parameters), One of them is Method
Name and second one is its Parameter list.

Method Naming : Name of a method or a function in any programming language whether in


C++ or Java or C# holds great importance and is mainly used in order to call that method for
its execution. For example, findSum, computeMax, setX and getX etc.

There are certain pre-defined rules for naming methods which a user should follow :

The method name must be some kind of Noun or a verb.


It’s naming should be done in such a way that it must describe the purpose of that method.

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>)

// Implementation of the method code goes here.....


}

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:

It completes all the statements in the method

It reaches a return statement

Throws an exception

Example : In the code below, a method named Sum() is called.

// C# program to illustrate method calling

using System;

namespace ConsoleApplication1 {

class ex {

// Here Sum() method asks for two parameters from the user and

// calculates the sum of these and finally returns the result.

static int Sum(int x, int y)

{
// there are two local variables 'a' and 'b' where 'a' is assigned the value of parameter

// 'x' and 'b' is assigned the value of parameter 'y'

int a = x;

int b = y;

// The local variable calculates the sum of 'a' and 'b' and returns the result

// which is of 'int' type.

int result = a + b;

return result;

// Main Method

static void Main(string[] args) {

int a = 12;

int b = 23;

// Method Sum() is invoked and the returned value is stored in the local variable say 'c'

int c = Sum(a, b);

// Display Result

Console.WriteLine("The Value of the sum is " + c);

} }

Output :

The Value of the sum is 35

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.

Example Program Without Parameters & Without Return Type

// C# program to illustrate method Without Parameters & Without Return Type

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.

static void PrintSentence() {

Console.WriteLine("No parameters and return type void");

// Main Method

static void Main(string[] args) {

// Method Invoking or Method calling

PrintSentence();

} }

Output :

No parameters and return type void

Example Program Without Parameters & With Return Value Type

// C# program to illustrate the method Without Parameters & With Return Value Type

using System;

namespace ConsoleApplication3 {

class ex {

// This method takes no parameter, however returns the result obtained

static int sum() {

int a = 78, b = 70, add;

add = a + b;

return add;

// Main Method

static void Main(string[] args) {

// Here the calling variable is 'getresult'


int getresult = sum();

// Printing the value of 'getresult' variable

Console.WriteLine(getresult);

} }

Output :

148

Example Program With Parameters & Without Return Value Type

// 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,

// it simply print it without returning anything..

static void perimeter(int p) {

// Displaying the perimeter of the square

Console.WriteLine("Perimeter of the Square is " + 4 * p);

// Main Method

static void Main(string[] args) {

// side of square

int p = 5;

// Method invoking

perimeter(p);

} }

Output :

Perimeter of the Square is 20

Example Program With Parameters & With Return Value Type


// C# program to illustrate Method With Parameters & With Return Value Type

using System;

namespace ConsoleApplication4 {

class ex {

// This method asks a number from the user and using that it calculates the factorial

// of it and returns the result

static int factorial(int n) {

int f = 1;

// Method to calculate the factorial of a number

for (int i = 1; i<= n; i++) {

f = f * i;

return f;

// Main Method

static void Main(string[] args) {

int p = 4;

// displaying result by calling the function

Console.WriteLine("Factorial is : " + factorial(p));

}}

Output:

Factorial is: 24

Advantages of using the Methods:

There are many advantages of using methods. Some of them are listed below:

It makes the program well structured.

Methods enhance the readability of the code.

It provides an effective way for the user to reuse the existing code.
It optimizes the execution time and memory space.
C# | Method Overloading

Method Overloading is the common way of implementing polymorphism. It is the ability to


redefine a function in more than one form.
A user can implement function overloading by defining two or more functions in a class
sharing the same name. C# can distinguish the methods with different method signatures. i.e.
the methods can have the same name but with different parameters list (i.e. the number of the
parameters, order of the parameters, and data types of the parameters) within the same class.
Overloaded methods are differentiated based on the number and type of the parameters passed
as arguments to the methods.
You can not define more than one method with the same name, Order and the type of the
arguments. It would be compiler error.
The compiler does not consider the return type while differentiating the overloaded method.
But you cannot declare two methods with the same signature and different return type.
It will throw a compile-time error. If both methods have the same parameter types, but
different return type, then it is not possible.
Why do we need Method Overloading?
If we need to do the same kind of the operation in different ways i.e. for different inputs. In the
example described below, we are doing the addition operation for different inputs. It is hard to
find many different meaningful names for single action.
Different ways of doing overloading methods-
Method overloading can be done by changing:
The number of parameters in two methods.
The data types of the parameters of methods.
The Order of the parameters of methods.

By changing the Number of Parameters


// C# program to demonstrate the function overloading by changing the Number of parameters
using System;
class ex {
// adding two integer values.
public int Add(int a, int b) {
int sum = a + b;
return sum;
}
// adding three integer values.
public int Add(int a, int b, int c) {
int sum = a + b + c;
return sum;
}
// Main Method
public static void Main(String[] args) {
// Creating Object
ex ob = new ex();
int sum1 = ob.Add(1, 2);
Console.WriteLine("sum of the two " + "integer value : " + sum1);
int sum2 = ob.Add(1, 2, 3);
Console.WriteLine("sum of the three " + "integer value : " + sum2);
}
}
Output:
sum of the two integer value : 3
sum of the three integer value : 6
By changing the Data types of the parameters
// C# program to demonstrate the function overloading by changing the Data types of the parameters
using System;
class ex {
// adding three integer values.
public int Add(int a, int b, int c) {
int sum = a + b + c;
return sum;
}
// adding three double values.
public double Add(double a, double b, double c) {
double sum = a + b + c;
return sum;
}
// Main Method
public static void Main(String[] args) {
// Creating Object
ex ob = new ex();
int sum2 = ob.Add(1, 2, 3);
Console.WriteLine("sum of the three " + "integer value : " + sum2);
double sum3 = ob.Add(1.0, 2.0, 3.0);
Console.WriteLine("sum of the three " + "double value : " + sum3);
}
}
Output:
sum of the three integer value : 6
sum of the three double value : 6
By changing the Order of the parameters
// C# program to demonstrate the function overloading by changing the Order of the parameters
using System;
class ex {
// Method
public void Identity(String name, int id) {
Console.WriteLine("Name1 : " + name + ", " + "Id1 : " + id);
}
// Method
public void Identity(int id, String name) {
Console.WriteLine("Name2 : " + name + ", " + "Id2 : " + id);
}
// Main Method
public static void Main(String[] args) {
// Creating Object
ex obj = new ex();

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 {

public void ex();

class derived_class : base_class {

public void ex();

class Main_Method {

static void Main() {

derived_class d = new derived_class();

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.

In C# we can use 3 types of keywords for Method Overriding:

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 derived_class : base_class {

public override void ex();

class Main_Method {

static void Main() {

derived_class d = new derived_class();

d.ex();

base_class b = new derived_class();

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.

A non-virtual or a static method can’t be overridden.


Both the override method and the virtual method must have the same access level modifier.

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.

Implicit Type Casting / Automatic Type Conversion

It happens when:

 The two data types are compatible.

 When we assign value of a smaller data type to a bigger data type.


For Example, in C#, the numeric data types are compatible with each other but no automatic
conversion is supported from numeric type to char or boolean. Also, char and boolean are not
compatible with each other. Before converting, the compiler first checks the compatibility
according to the following figure and then it decides whether it is alright or there some error.
Following table shows the implicit types of conversion that is supported by C# :

Convert from Data Type Convert to Data Type

byte short, int, long, float, double

short int, long, float, double

int long, float, double

long float, double

float double

Example :

// C# program to demonstrate the Implicit Type Conversion

using System;

namespace Casting {

class ex {

// Main Method

public static void Main(String []args) {

int i = 57; // automatic type conversion

long l = i; // automatic type conversion

float f = l;

Console.WriteLine("Int value " +i);

Console.WriteLine("Long value " +l);

Console.WriteLine("Float value " +f);

} }

Output:

Int value 57

Long value 57

Float value 57

Explicit Type Casting


There may be compilation error when types not compatible with each other. For example,
assigning double value to int data type:

// C# program to illustrate incompatible datatype for explicit type conversion

using System;

namespace Casting{

class ex{

// Main Method

public static void Main(String []args) {

double d = 765.12;

// Incompatible Data Type

int i = d;

// Display Result

Console.WriteLine("Value of i is ", +i);

} }

Error :

prog.cs(14,21): error CS0266: Cannot implicitly convert type `double' to `int'.

An explicit conversion exists (are you missing a cast?)

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.

Sometimes, it may result into the lossy conversion.

Example :

// C# program to demonstrate the Explicit Type Conversion

using System;

namespace Casting{

class ex {

// Main Method
public static void Main(String []args) {

double d = 765.12;

// Explicit Type Casting

int i = (int)d;

// Display Result

Console.WriteLine("Value of i is " +i);

} }

Output:
Value of i is 765

You might also like