AWP Notes
AWP Notes
UNIT-I
Introducing .NET: The .NET Framework, C#, VB, and the .NET Languages, The Common
Language Runtime, The .NET Class Library.
The C# Language: C# Language Basics, Variables and Data Types, Variable Operations,
Object-Based Manipulation, Conditional Logic, Loops, Methods.
Types, Objects, and Namespaces: The Basics About Classes, Building a Basic Class, Value
Types and Reference Types, Understanding Namespaces and Assemblies, Advanced Class
Programming.
--------------------------------------------------------------------------------------------------------------------------
.NET framework:
The .NET Framework is a development platform for building apps for web, Windows, Windows Phone,
Windows Server, and Microsoft Azure. It consists of the common language runtime (CLR) and the .NET
Framework class library, which includes a broad range of functionality and support for many industry
standards.
The .NET Framework provides many services, including memory management, type and memory
safety, security, networking, and application deployment. It provides easy-to-use data structures and
APIs that abstract the lower-level Windows operating system. You can use a variety of programming
languages with the .NET Framework, including C#, F#, and Visual Basic.
Components of the .Net Framework:
(i) User Interface and Program:
We can create various types of applications using .net framework such as Console
Application, Windows Application, Web application and Mobile Applications.
(ii) CLS
It is a subset of CTS. It defines a set of rules and restrictions that every language must follow which
runs under .NET framework. The languages which follow these set of rules are said to be CLS
Compliant. In simple words, CLS enables cross-language integration.
(iii) MSIL/IL/CIL
It is language independent code. When you compile code that uses the .NET Framework library, you
don’t immediately create an operating system - specific native code. Instead, you compile your code
into Microsoft Intermediate Language (MSIL) code or simply IL code. MSIL code is not specific to any
operating system or to any language.
Components .NET CLR and their functions
The key components of CLR includes the following:
Generations
The heap is organized into generations so it can handle long-lived and short-lived objects. Garbage
collection primarily occurs with the reclamation of short-lived objects that typically occupy only a small
part of the heap.
Generation 1. This serves as a buffer between short-lived objects and long-lived objects.
Execution of C# code:
The .NET Class Library (framework base class library):
Answer: .NET supplies a library of base classes that we can use to implement applications
quickly. We can use them by simply instantiating them & invoking their methods or by inheriting
them through derived classes, thus extending their functionality.
Much of the functionality in the base framework classes resides in the vast namespace called
System. We can use the base classes in the system namespaces for many different tasks
including:
➢ Input/Output Operations.
➢ String handling.
➢ Managing arrays, lists, maps etc.
➢ Accessing files & file systems.
➢ Accessing the registry.
➢ Security.
➢ Windowing.
➢ Windows messages.
➢ Database Management.
➢ Drawing.
➢ Managing errors & exceptions.
➢ Connecting to the Internet.
VB.NET C#
Both languages are functionally equal. Both languages are functionally equal.
Each statement does not end with a Each statement is terminated with a
semicolon. semicolon (;)
The C# Language:
First C# Program:
namespace HelloWorld
{
class Hello
{
static void Main(string[] args)
{
Console.Write("Hello World!");
Console.ReadLine();
}
}
}
Above program consists of the following elements
(i) Namespace
(ii) Comment
(iii) Class
(iV) Main() method
(v) Write() method
(vi) ReadLine() method
There are two kinds of types in C#: value types and reference types. Variables of value types
directly contain their data whereas variables of reference types store references to their data,
the latter being known as objects. With reference types, it's possible for two variables to
reference the same object and thus possible for operations on one variable to affect the object
referenced by the other variable. With value types, the variables each have their own copy of
the data, and it isn't possible for operations on one to affect the other (except for ref and out
parameter variables).
C#'s value types are further divided into simple types, enum types, struct types, and nullable
value types. C#'s reference types are further divided into class types, interface types, array
types, and delegate types.
C# - Variables:
A variable nothing but a name given to a storage area that our programs can manipulate. Each
variable in C# has a specific type, which determines the size of the memory required to store data.
Syntax:
<data type> <variable name> = <value>;
For example,
int num;
Console.WriteLine(“Enter a value:”);
num = Convert.ToInt32(Console.ReadLine());
The function Convert.ToInt32() converts the data entered by the user to int data type, because
Console.ReadLine() accepts the data in string format.
C# Type Casting
Type casting is when you assign a value of one data type to another type.
In C#, there are two types of casting:
● Implicit Casting (automatically) - converting a smaller type to a larger type size
char -> int -> long -> float -> double
Implicit Casting
Implicit casting is done automatically when passing a smaller size type to a larger size type:
Example
int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double
Console.WriteLine(myInt); // Outputs 9
Console.WriteLine(myDouble); // Outputs 9
Explicit Casting
Explicit casting must be done manually by placing the type in parentheses in front of the value:
Example
double myDouble = 9.78;
int myInt = (int)myDouble; // Manual casting: double to int
Note that the boxing operation creates a copy of the value of the m integer to the object om.
Both the variables exist but the value of om resides on the heap. This means that the values
are independent of each other.
Example
int m =10;
object om = m;
m = 20;
Console.WriteLine(m); // m= 20
Console .WriteLine(om); //om=10
Unboxing:
Unboxing is the process of converting the object type back to the value type. Remember that a
variable can be unboxed only if it has been previously boxed. In contrast to boxing, unboxing is
an explicit operation.
Example:-
int m = 100;
object om = m; //boxing
int n = (int) om; //unboxing
When performing unboxing, C# checks the value type we request is actually stored in the
object under conversion. Only if it is, the value is unboxed.
C# Namespaces:
Namespaces are used in C# to organize and provide a level of separation of codes. They can be
considered as a container which consists of other namespaces, classes, etc.
A namespace can have following types as its members such as Namespaces (Nested Namespace),
Classes, Interfaces, Structures, Delegates
Syntax:
A namespace definition begins with the keyword namespace followed by the
namespace name as follows:
namespace Namespace-Name
{
//Body of namespace
}
Example:
using System;
namespace First
{
public class Hello
{
public void sayHello()
{
Console.WriteLine("Hello First Namespace");
}
}
}
namespace Second
{
public class Hello
{
public void sayHello()
{
Console.WriteLine("Hello Second Namespace");
}
}
}
public class TestNamespace
{
public static void Main()
{
First.Hello h1 = new First.Hello();
Second.Hello h2 = new Second.Hello();
h1.sayHello();
h2.sayHello();
}
}
For example,
We are using the System namespace in our program. The class Console is defined there. We just
write:
System.Console.WriteLine("Hello there");
Alias of Namespace:
using A=System.Console;
class Test
{
static void Main()
{
A.Write("Creation of Alias");
A.ReadKey();
}
}
C# supports a number of operators that are classified based on the type of operations they
perform.
Arithmetic Operators:
Modulo Operator
% 16 % 3 evaluates to 1
(Remainder)
Example:
using System;
namespace Operator
{
class ArithmeticOperator
{
public static void Main(string[] args)
{
double num1 = 14.40, num2 = 4.60, result;
//int num1 = 26, num2 = 4, rem;
// Addition operator
result = num1 + num2;
Console.WriteLine("{0} + {1} = {2}", num1, num2, result);
// Subtraction operator
result = num1 - num2;
Console.WriteLine("{0} - {1} = {2}", num1, num2, result);
// Multiplication operator
result = num1 * num2;
Console.WriteLine("{0} * {1} = {2}", num1, num2, result);
// Division operator
result = num1 / num2;
Console.WriteLine("{0} / {1} = {2}", num1, num2, result);
// Modulo operator
rem = num1 % num2;
Console.WriteLine("{0} % {1} = {2}", num1, num2, rem);
}
}
}
OUTPUT:
14.4 + 4.6 = 19
14.4 - 4.6 = 9.8
14.4 * 4.6 = 66.24
14.4 / 4.6 = 3.1304347826087
26 % 4 = 2
Relational Operators:
Relational operators are used to check the relationship between two operands. If the relationship is
true the result will be true, otherwise it will result in false.Relational operators are used in decision
making and loops.
using System;
namespace Operator
{
class RelationalOperator
{
public static void Main(string[] args)
{
bool result;
int num1 = 10, num2 = 20;
result = (num1==num2);
Console.WriteLine("{0} == {1} returns {2}",num1, num2, result);
OUTPUT:
10 == 20 returns False
10 > 20 returns False
10 < 20 returns True
10 >= 20 returns False
10 <= 20 returns True
10 != 20 returns True
Logical Operators
Logical operators are used to perform logical operations such as and, or. Logical operators operate
on boolean expressions (true and false) and return boolean values. Logical operators are used in
decision making and loops.
Here is how the result is evaluated for logical AND and OR operators.
// OR operator
result = (n1 == n2) || (n1 > 5);
Console.WriteLine(result);
// AND operator
result = (n1 == n2) && (n1 > 5);
Console.WriteLine(result);
}
}
}
Output:
True
False
Difference between for and foreach loop:
for loop foreach loop
1 In case of a for loop control variable of 1 In case of foreach the control variable of
the loop is always be int only. the loop is the same as the type of values
under the array.
2 The for loop executes the statement or 2 The foreach statement repeats a group of
block of statements repeatedly until embedded statements for each element
specified expression evaluates to false. in an array or an object collection.
3 There is need to specify the loop 3 We do not need to specify the loop
bounds(Minimum, Maximum). bounds (Minimum, Maximum).
4 For loop is complex than foreach loop 4 Foreach loop is simple than for loop
Let's see the example of array where we are declaring and initializing array at the same time.
using System;
public class ArrayExample
{
public static void Main(string[] args)
{
char[] arr = { ‘a’, ‘m’, ‘a’, ‘n’ };//Declaration and Initialization of array
//traversing array
for (int i = 0; i < arr.Length; i++)
{
Console.WriteLine(arr[i]);
}
foreach(char n in arr)
{
Console.WriteLine(n);
}
}
}
Output:
10
20
30
40
50
Jagged Array:
In a variable sized array, each row may have different number of columns. It is equivalent to an
array of variable sized one-dimensional arrays. The Length property is used to get the length
of each one-dimensional array. A variable sized array is also known as a jagged array.
Example:
class numadd
{
public static void Main()
{
int[][] x=new int[4][];
x[0]=new int[2]{5,13};
x[1]=new int[3]{7,8,11};
x[2]=new int[4]{2,3,4,5};
x[3]=new int[1]{9};
for(int i=0;i<4;i++)
{
for(int j=0;j<x[i].Length;j++)
{
Console.Write(x[i][j]+"\t");
}
Console.Write("\n");
}
}
This topic describes two methods for controlling program flow — that is, the order of
execution of lines of C# code: branching and looping. Branching executes code
conditionally, depending on the outcome of an evaluation, such as ‘‘only execute this code if
the variable myVal is less than 10.’’ Looping repeatedly executes the same statements, either
a certain number of times or until a test condition has been reached.
Both of these techniques involve the use of Boolean logic.
Break statement:
When the break statement is encountered inside a loop, the loop is immediately terminated and
program control resumes at the next statement following the loop.
It can be used to terminate a case in the switch statement.
while(test-condition)
{
---
---
if(condition)
break;
---
---
}
stat-x;
---
---
Continue statement: Continue statement tells the compiler “SKIP THE FOLLOWING STATEMENT(S)
AND CONTINUE WITH THE NEXT ITERATION”. Causes the current loop cycle to end immediately
(execution continues with the next loop cycle).
Example:
while(test-condition)
{
---
---
if(condition)
continue;
---
--- skip
}
Example:
class Program
{
static void Main(string[] args)
{
int i;
for (i = 0; i <= 10; i++)
{
if (i == 5)
continue;
if (i == 8)
break;
When the above code is compiled and executed, it produces the following result −
value is: 0
value is: 1
value is: 2
value is: 3
value is: 4
value is: 6
value is: 7
As an example, every type in the .NET class library includes a ToString() method. The default
implementation of ‘this’ method returns the class name.
The following code snippet demonstrates how to use the ToString() method with an integer:
string VMyString;
int vMyInteger=100;
vMyString=vMyInteger.ToString();
params: In C#, params is a keyword which is used to specify a parameter that takes a
variable number of arguments. It is useful when we don't know the number of arguments
prior. Only one Params keyword is allowed and no additional Params will be allowed in
function declaration after a params keyword. The length of params will be zero if no
arguments will be passed.
ref: The ref keyword is used to pass an argument as a reference. This means that when
the value of that parameter is changed in the method, it gets reflected in the calling
method. An argument that is passed using a ref keyword must be initialized in the calling
method before it is passed to the called method..
out: The out keyword is also used to pass an argument like ref keyword, but the
argument can be passed without assigning any value to it. An argument that is passed
using an out keyword must be initialized in the called method before it returns back to
calling method.
Ref parameter:
using System;
namespace CalculatorApplication {
class NumberManipulator {
public void swap(ref int x, ref int y)
{
int temp;
temp = x; /* save the value of x */
x = y; /* put y into x */
y = temp; /* put temp into y */
}
Console.ReadLine();
}
}
}
Output
Before swap, value of a : 100
Before swap, value of b : 200
After swap, value of a : 200
After swap, value of b : 100
Out Parameter:
namespace MyNamespace
{
class Program
{
static void Main(string[] args)
{
int x, y;
Multiplication(out x, out y); // Function call
b = 200;
}
}
}
Difference between Ref and Out keywords
REF KEYWORD OUT KEYWORD
The passing of value through the ref parameter is The declaration of parameters through
useful when the called method also needs to the out parameter is useful when a
change the value of the passed parameter. method returns multiple values.
When ref keyword is used the data may pass in When out keyword is used the data
bi-directional. only passed in unidirectional.
Params Parameter:
public class MyClass
{
public static void UseParams(params int[] list)
{
for (int i = 0; i < list.Length; i++)
{
Console.Write(list[i] + " ");
}
Console.WriteLine();
}
// An array argument can be passed, as long as the array type matches the parameter type of the
method being called.
int[] myIntArray = { 5, 6, 7, 8, 9 };
UseParams(myIntArray);
56789
2 b test again
*/
The derived class method that overrides the base class method should be marked with the keyword
override.
Example:
using System;
class A
{
public void Test()
{
Console.WriteLine("A::Test()");
}
}
class B : A
{
Public override void Test()
{
Console.WriteLine("B::Test()");
}
}
class C : B
{
public override void Test() { Console.WriteLine("C::Test()"); }
}
class Program
{
static void Main(string[] args)
{
A a = new A();
B b = new B();
C c = new C();
a.Test(); // output --> "A::Test()"
b.Test(); // output --> "B::Test()"
c.Test(); // output --> "C::Test()"
a = new B();
a.Test(); // output --> "B::Test()"
b = new C();
b.Test(); // output --> "C::Test()"
Console.ReadKey();
}
}
Difference between overloading and overriding:
Overloading Overriding
Static methods can be overloaded which Static methods cannot be overridden, even if
means a class can have more than one static you declare the same static method in child
method of the same name. class it has nothing to do with the same
method of parent class.
Overloading is being done in the same class For overriding base and child classes are
required
Static binding is being used for overloaded Dynamic binding is being used for
methods overridden/overriding methods.
Private and final methods can be overloaded. It Private and final methods cannot be
means a class can have more than one overridden. It means a child class cannot
private/final methods of same name override the private/final methods of their base
class.
Return type of method does not matter in case However in case of method overriding the
of method overloading, it can be the same or overriding method can have more specific
different. return type.
What are sealed classes and sealed methods? Why are they used?
This is a method that is declared with the keyword sealed and is always used with an override
keyword. Such method provides a complete implementation to its base class virtual method using the
override keyword. Prevent overriding a method of a class. Derived classes will not be able to
override further this method as it is sealed for overriding.
Characteristics
● A method cannot be defined as sealed unless that method is an override of a method in its base
class.
● A sealed method cannot be overridden further.
● Sealed methods are useful to avoid problems caused by overriding the existing functionality.
● It prevents the user from changing the internal functionality of a class.
Example:
using System;
class A
{
public virtual void F()
{
Console.WriteLine("A.F");
}
public virtual void G()
{
Console.WriteLine("A.G");
}
}
class B: A
{
sealed override public void F()
{
Console.WriteLine("B.F");
}
override public void G()
{
Console.WriteLine("B.G");
}
}
class C: B
{
override public void G()
{
Console.WriteLine("C.G");
}
}
The class B provides two override methods: an F method that has the sealed modifier and a G
method that does not. B's use of the sealed modifier prevents C from further overriding F.
Sealed Class:
A sealed class cannot be inherited. Means, no class can be derived from a sealed
class. To make a class sealed, we use the keyword sealed in class declaration. For
example, if we seal class A as below source code then class B cannot be derived from
it. One question arises immediately that can we create object of sealed class in C#
program? Answer is, of course we can create objects of a sealed class. Purpose of
sealed class is only to prevent a class to be inherited.
Example:
using System;
sealed class MyClass
{
public int x;
public int y;
}
class MainClass
{
public static void Main()
{
MyClass mC = new MyClass();
mC.x = 110;
mC.y = 150;
Console.WriteLine("x = {0}, y = {1}", mC.x, mC.y);
}
}
Abstract Method
A method which is declared abstract and has no body is called an abstract method. It can be
declared inside the abstract class only. Its implementation must be provided by derived classes.
For example:
public abstract void draw();
Note: An abstract method in C# is internally a virtual method so it can be overridden by the derived
class.
Abstract Class:
In C#, abstract class is a class which is declared abstract. It can have abstract and non-abstract
methods. It cannot be instantiated. Its implementation must be provided by derived classes. Here, the
derived class is forced to provide the implementation of all the abstract methods.
You can derive both abstract and non-abstract classes from an abstract base class. Interfaces are
implicitly abstract.
using System;
public abstract class Shape
{
public abstract void draw();
}
public class Rectangle : Shape
{
public override void draw()
{
Console.WriteLine("drawing rectangle...");
}
}
public class Circle : Shape
{
public override void draw()
{
Console.WriteLine("drawing circle...");
}
}
public class TestAbstract
{
public static void Main()
{
Shape s;
s = new Rectangle();
s.draw();
s = new Circle();
s.draw();
}
}
Output:
drawing ractangle...
drawing circle...
C# Interface:
Interface in C# is a blueprint of a class. It is like an abstract class because all the methods which are
declared inside the interface are abstract methods. It cannot have a method body and cannot be
instantiated.
It is used to achieve multiple inheritance which can't be achieved by class. It is used to achieve full
abstraction because it cannot have a method body.
Its implementation must be provided by class or struct. The class or struct which implements the
interface, must provide the implementation of all the methods declared inside the interface.
using System;
public interface Drawable
{
void draw();
}
public class Rectangle : Drawable
{
public void draw()
{
Console.WriteLine("drawing rectangle...");
}
}
public class Circle : Drawable
{
public void draw()
{
Console.WriteLine("drawing circle...");
}
}
public class TestInterface
{
public static void Main()
{
Drawable d;
d = new Rectangle();
d.draw();
d = new Circle();
d.draw();
}
}
Output:
drawing ractangle...
drawing circle...
Switch statement:
Use the switch statement to select one of many code blocks to be executed. The switch statement is
an alternative to if else statement.
Syntax:
switch(expression)
{
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
break;
}
This is how it works:
● The switch expression is evaluated once.
● The switch expression is of integer type such as int, char, byte, or short, or of an enumeration
type, or of string type.
● The value of the expression is compared with the values of each case label.
● If there is a match, the associated block of code is executed.
● break causes the termination of the switch statement.
● default marks the block that would get executed if the switch expression does not
match any case labels.
●
Example:
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int day= 4;
switch (day)
{
case 1:
Console.WriteLine("Monday");
break;
case 2:
Console.WriteLine("Tuesday");
break;
case 3:
Console.WriteLine("Wednesday");
break;
case 4:
Console.WriteLine("Thursday");
break;
case 5:
Console.WriteLine("Friday");
break;
case 6:
Console.WriteLine("Saturday");
break;
case 7:
Console.WriteLine("Sunday");
break;
}
}
}
}
using System;
class Program
{
static void Main()
{
int value = 0;
// ... Every switch statement must be terminated.
switch (value)
{
case 0:
Console.WriteLine("Zero");
case 1:
Console.WriteLine("One");
break;
}
}
}
Output
Error 1
Control cannot fall through from one case label ('case 0:') to another.
in C#:
In C#, collection represents a group of objects. By the help of collections, we can perform various
operations on objects such as insert, delete, search, modify etc.
The System.Collections namespace has following classes:
CLASS
DESCRIPTION
NAME
It is a dynamic array means the size of the array is not fixed, it can increase
ArrayList
and decrease at runtime.
It is a linear data structure. It follows the LIFO(Last In, First Out) pattern for
Stack
Input/output.
ArrayList Collection:
The ArrayList in C# is a collection class that works like an array but provides the facilities such as
dynamic resizing, adding and deleting elements from the middle of a collection. It implements the
System.Collections.IList interface using an array whose size is dynamically increased as required.
Properties:
● Capacity: This property gives you the capacity of the collection means how many
elements you can insert into the collection.
● Count: This property gives you the number of elements present in a collection.
using System;
using System.Collections;
namespace ArrayListCollection
{
class Program
{
static void Main(string[] args)
{
//Creating ArrayList collection using default constructor
ArrayList al = new ArrayList();
Output:
Initial Capacity: 0
Capacity after adding first item: 4
Capacity after adding fourth item: 4
Capacity after adding 5th element: 8
10 hello True 3.14 A
10 hello 3.14 A
10 hello False 3.14 A
Initial capacity of new array list collection:5
10 hello False 3.14 A
You have applied to the University Portal for FY B. Sc (IT) admission & selected VPMs RZ Shah
College Mulund. Now submit online application form to our college, if you have not yet applied on
www.vpmrzshahcollege.edu.in
Usually inside a class, we declare a data field as private and will provide a set of public SET
and GET methods to access the data fields.
In C#, properties are defined using the property declaration syntax. The general form of
declaring a property is as follows.
Example:
using System;
class MyClass
{
private int x;
public int A // A is name of the property
{
set
{
x = value; // value is a keyword
}
get
{
return x;;
}
}
}
class MyClient
{
public static void Main()
{
MyClass mc = new MyClass();
mc.X = 10;
int xVal = mc.X;
Console.WriteLine(xVal);//Displays 10
}
}
Type Metadata:
Metadata describes the contents in an assembly. In addition to containing MSIL, assemblies
also include meta information (that is, information about the information contained in the
assembly, also known as metadata ) and optional resources (additional data used by the MSIL,
such as sound files and pictures). The meta information enables assemblies to be fully
self-descriptive. You need no other information to use an assembly, meaning you avoid
situations such as failing to add required data to the system registry and so on, which was often
a problem when developing with other platforms.
MSIL:
It contains Intermediate language code.
Resources:
It contains bitmaps, icons, audios and other types of resources.
There are two types of assemblies: private and shared. A private assembly can be used by
only a single application. A shared assembly, on the other hand, can be used by all applications
located on the same server.
Shared assemblies are located in the Global Assembly Cache (GAC). For example, the
System.Web.dll assembly and all the other assemblies included with the .NET Framework are
located in the Global Assembly Cache.
Private assembly can be used by only one Public assembly can be used by multiple
application. applications.
Private assembly will be stored in the specific Public assembly is stored in GAC (Global
application's directory or sub-directory/root Assembly Cache).
directory.
There is no other name for private assembly. Public assembly is also termed as shared
assembly.
Strong name is not required for private assembly. Strong name has to be created for public
assembly.
Private assembly doesn't have any version Public assembly should strictly enforce version
constraint. constraint.
The dll or exe which is sole property of one It is a dll which can be used by multiple
application only. applications at a time.
Note:
The Global Assembly Cache is located physically in your computer's \WINDOWS\Assembly folder.
There is a separate copy of every assembly in your
C:\Windows\Microsoft.NET\Framework\v4.0.30319 folder. The first set of assemblies is used at
runtime and the second set is used at compile time.
Unmanaged code is any code that does not depend on CLR for execution. It means it is developed by
any other language independent of .Net framework. It uses its own runtime environment for compiling
and execution.
Though it is not running inside the CLR, the unmanaged code will work properly if all the other
parameters are correctly followed.
Hiding methods:
To hide base class methods in derived classes we can declare derived class methods with new
keyword. To use new keyword, we need to write the code like as shown below
Example:-
class SampleA
{
public void Show()
{
Console.WriteLine("Sample A Test Method");
}
}
class SampleB:SampleA
{
public new void Show()
{
Console.WriteLine("Sample B Test Method");
}
}
class Program
{
static void Main(string[] args)
{
SampleA a=new SampleA();
SampleB b=new SampleB();
a.Show();
b.Show();
a = new SampleB();
a.Show();
Console.ReadLine();
}
}
class DelegateEx
{
// Declaring the delegates
public delegate void addnum(int a, int b);
public delegate void subnum(int a, int b);
// Defining delegate methods
public void sum(int a, int b)
{
Console.WriteLine("(100 + 40) = {0}", a + b);
}
Multicast Delegate:
Multicast Delegate is an extension of normal delegates. It combines more than one method at a
single moment of time.
1. In Multicasting, Delegates can be combined and when you call a delegate, a whole list of
methods is called.
2. void is used as return type
3. out parameter is not allowed as arguments
4. All methods are called in FIFO (First in First Out) order.
5. + or += Operator is used for adding methods to delegates.
6. – or -= Operator is used for removing methods from the delegates list
m1=m1+m2+m1+m2-m1;
m1();
Console.Read();
}
}
OUTPUT:
New Delhi
New York
New York
1. using System;
2. delegate int Calculator(int n);//declaring delegate
3.
4. public class DelegateExample
5. {
6. static int number = 100;
7. public static int add(int n)
8. {
9. number = number + n;
10. return number;
11. }
12. public static int mul(int n)
13. {
14. number = number * n;
15. return number;
16. }
17. public static int getNumber()
18. {
19. return number;
20. }
21. public static void Main(string[] args)
22. {
23. Calculator c1 = new Calculator(add);//instantiating delegate
24. Calculator c2 = new Calculator(mul);
25. c1(20);//calling method using delegate
26. Console.WriteLine("After c1 delegate, Number is: " + getNumber());
27. c2(3);
28. Console.WriteLine("After c2 delegate, Number is: " + getNumber());
29.
30. }
31.}