SlideShare uma empresa Scribd logo
1 de 4
Baixar para ler offline
http://www.tutorialspoint.com/csharp/csharp_generics.htm Copyright © tutorialspoint.com
C# - GENERICS
Generics allow you to delay the specification of the data type of programming elements in a class or a method, until it
is actually used in the program. In other words, generics allow you to write a class or method that can work with any
data type.
You write the specifications for the class or the method, with substitute parameters for data types. When the compiler
encounters a constructor for the class or a function call for the method, it generates code to handle the specific data
type. A simple example would help understanding the concept:
using System;
using System.Collections.Generic;
namespace GenericApplication
{
public class MyGenericArray<T>
{
private T[] array;
public MyGenericArray(int size)
{
array = new T[size + 1];
}
public T getItem(int index)
{
return array[index];
}
public void setItem(int index, T value)
{
array[index] = value;
}
}
class Tester
{
static void Main(string[] args)
{
//declaring an int array
MyGenericArray<int> intArray = new MyGenericArray<int>(5);
//setting values
for (int c = 0; c < 5; c++)
{
intArray.setItem(c, c*5);
}
//retrieving the values
for (int c = 0; c < 5; c++)
{
Console.Write(intArray.getItem(c) + " ");
}
Console.WriteLine();
//declaring a character array
MyGenericArray<char> charArray = new MyGenericArray<char>(5);
//setting values
for (int c = 0; c < 5; c++)
{
charArray.setItem(c, (char)(c+97));
}
//retrieving the values
for (int c = 0; c< 5; c++)
{
Console.Write(charArray.getItem(c) + " ");
}
Console.WriteLine();
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces following result:
0 5 10 15 20
a b c d e
Features of Generics
Using generics is a technique that enriches your programs in the following ways:
It helps you to maximize code reuse, type safety, and performance.
You can create generic collection classes. The .NET Framework class library contains several new generic
collection classes in the System.Collections.Generic namespace. You may use these generic collection classes
instead of the collection classes in the System.Collections namespace.
You can create your own generic interfaces, classes, methods, events and delegates.
You may create generic classes constrained to enable access to methods on particular data types.
You may get information on the types used in a generic data type at run-time by means of reflection.
Generic Methods
In the previous example, we have used a generic class; we can declare a generic method with a type parameter. The
following program illustrates the concept:
using System;
using System.Collections.Generic;
namespace GenericMethodAppl
{
class Program
{
static void Swap<T>(ref T lhs, ref T rhs)
{
T temp;
temp = lhs;
lhs = rhs;
rhs = temp;
}
static void Main(string[] args)
{
int a, b;
char c, d;
a = 10;
b = 20;
c = 'I';
d = 'V';
//display values before swap:
Console.WriteLine("Int values before calling swap:");
Console.WriteLine("a = {0}, b = {1}", a, b);
Console.WriteLine("Char values before calling swap:");
Console.WriteLine("c = {0}, d = {1}", c, d);
//call swap
Swap<int>(ref a, ref b);
Swap<char>(ref c, ref d);
//display values after swap:
Console.WriteLine("Int values after calling swap:");
Console.WriteLine("a = {0}, b = {1}", a, b);
Console.WriteLine("Char values after calling swap:");
Console.WriteLine("c = {0}, d = {1}", c, d);
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces following result:
Int values before calling swap:
a = 10, b = 20
Char values before calling swap:
c = I, d = V
Int values after calling swap:
a = 20, b = 10
Char values after calling swap:
c = V, d = I
Generic Delegates
You can define a generic delegate with type parameters. For example:
delegate T NumberChanger<T>(T n);
The following example shows use of this delegate:
using System;
using System.Collections.Generic;
delegate T NumberChanger<T>(T n);
namespace GenericDelegateAppl
{
class TestDelegate
{
static int num = 10;
public static int AddNum(int p)
{
num += p;
return num;
}
public static int MultNum(int q)
{
num *= q;
return num;
}
public static int getNum()
{
return num;
}
static void Main(string[] args)
{
//create delegate instances
NumberChanger<int> nc1 = new NumberChanger<int>(AddNum);
NumberChanger<int> nc2 = new NumberChanger<int>(MultNum);
//calling the methods using the delegate objects
nc1(25);
Console.WriteLine("Value of Num: {0}", getNum());
nc2(5);
Console.WriteLine("Value of Num: {0}", getNum());
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces following result:
Value of Num: 35
Value of Num: 175

Mais conteúdo relacionado

Mais procurados

Csharp4 delegates lambda_and_events
Csharp4 delegates lambda_and_eventsCsharp4 delegates lambda_and_events
Csharp4 delegates lambda_and_events
Abed Bukhari
 

Mais procurados (20)

Vector class in C++
Vector class in C++Vector class in C++
Vector class in C++
 
Csharp4 delegates lambda_and_events
Csharp4 delegates lambda_and_eventsCsharp4 delegates lambda_and_events
Csharp4 delegates lambda_and_events
 
Templates
TemplatesTemplates
Templates
 
C++ theory
C++ theoryC++ theory
C++ theory
 
Java part 2
Java part  2Java part  2
Java part 2
 
functions in C
functions in Cfunctions in C
functions in C
 
Arrays in c
Arrays in cArrays in c
Arrays in c
 
C standard library functions
C standard library functionsC standard library functions
C standard library functions
 
Array ppt
Array pptArray ppt
Array ppt
 
Introduction to c programming
Introduction to c programmingIntroduction to c programming
Introduction to c programming
 
Programming in c Arrays
Programming in c ArraysProgramming in c Arrays
Programming in c Arrays
 
Method parameters in c#
Method parameters in c#Method parameters in c#
Method parameters in c#
 
Pointers in C language
Pointers  in  C languagePointers  in  C language
Pointers in C language
 
Arrays in C language
Arrays in C languageArrays in C language
Arrays in C language
 
Memory Management C++ (Peeling operator new() and delete())
Memory Management C++ (Peeling operator new() and delete())Memory Management C++ (Peeling operator new() and delete())
Memory Management C++ (Peeling operator new() and delete())
 
Java8: what's new and what's hot
Java8: what's new and what's hotJava8: what's new and what's hot
Java8: what's new and what's hot
 
C++ lecture 04
C++ lecture 04C++ lecture 04
C++ lecture 04
 
Comp 328 final guide
Comp 328 final guideComp 328 final guide
Comp 328 final guide
 
C++lecture9
C++lecture9C++lecture9
C++lecture9
 
C++ Returning Objects
C++ Returning ObjectsC++ Returning Objects
C++ Returning Objects
 

Destaque

FUKUYAMA BASE WORKSHOP Vol14 Theme
FUKUYAMA BASE WORKSHOP Vol14 ThemeFUKUYAMA BASE WORKSHOP Vol14 Theme
FUKUYAMA BASE WORKSHOP Vol14 Theme
noteproject
 
The Aligned Agenda -Insights From Cfo And Cio Studies
The Aligned Agenda -Insights From Cfo And Cio StudiesThe Aligned Agenda -Insights From Cfo And Cio Studies
The Aligned Agenda -Insights From Cfo And Cio Studies
manish gupta
 
Investor communications highlights
Investor communications highlightsInvestor communications highlights
Investor communications highlights
Peter Gallagher
 
Behavioural Marketing…or how to get your customers to love you
Behavioural Marketing…or how to get your customers to love youBehavioural Marketing…or how to get your customers to love you
Behavioural Marketing…or how to get your customers to love you
John Watton
 
Open Day Presentation
Open Day Presentation Open Day Presentation
Open Day Presentation
sallyross
 
3 different methods to publicise our presentation
3 different methods to publicise our presentation3 different methods to publicise our presentation
3 different methods to publicise our presentation
sathma
 
Detailed Pros and Cons of presenting either units
Detailed Pros and Cons of presenting either unitsDetailed Pros and Cons of presenting either units
Detailed Pros and Cons of presenting either units
sathma
 

Destaque (20)

FUKUYAMA BASE WORKSHOP Vol14 Theme
FUKUYAMA BASE WORKSHOP Vol14 ThemeFUKUYAMA BASE WORKSHOP Vol14 Theme
FUKUYAMA BASE WORKSHOP Vol14 Theme
 
The Aligned Agenda -Insights From Cfo And Cio Studies
The Aligned Agenda -Insights From Cfo And Cio StudiesThe Aligned Agenda -Insights From Cfo And Cio Studies
The Aligned Agenda -Insights From Cfo And Cio Studies
 
Memphis Memories
Memphis MemoriesMemphis Memories
Memphis Memories
 
Mn powerpoint
Mn powerpointMn powerpoint
Mn powerpoint
 
Онлайн консультирование практикующих психологов
Онлайн консультирование практикующих психологовОнлайн консультирование практикующих психологов
Онлайн консультирование практикующих психологов
 
Investor communications highlights
Investor communications highlightsInvestor communications highlights
Investor communications highlights
 
Black Men Speak, Inc Workshop Dec 2013
Black Men Speak, Inc Workshop Dec 2013 Black Men Speak, Inc Workshop Dec 2013
Black Men Speak, Inc Workshop Dec 2013
 
Behavioural Marketing…or how to get your customers to love you
Behavioural Marketing…or how to get your customers to love youBehavioural Marketing…or how to get your customers to love you
Behavioural Marketing…or how to get your customers to love you
 
Open Day Presentation
Open Day Presentation Open Day Presentation
Open Day Presentation
 
Ana
AnaAna
Ana
 
FUKUYAMA BASE WORKSHOP Vol16 Theme
FUKUYAMA BASE WORKSHOP Vol16 ThemeFUKUYAMA BASE WORKSHOP Vol16 Theme
FUKUYAMA BASE WORKSHOP Vol16 Theme
 
Ppt qa 2
Ppt qa 2Ppt qa 2
Ppt qa 2
 
Big Data Expertise
Big Data ExpertiseBig Data Expertise
Big Data Expertise
 
3 different methods to publicise our presentation
3 different methods to publicise our presentation3 different methods to publicise our presentation
3 different methods to publicise our presentation
 
Hotspot
HotspotHotspot
Hotspot
 
Network Layered Models Rroosend
Network Layered Models RroosendNetwork Layered Models Rroosend
Network Layered Models Rroosend
 
Infobroker czy detektyw
Infobroker czy detektywInfobroker czy detektyw
Infobroker czy detektyw
 
Detailed Pros and Cons of presenting either units
Detailed Pros and Cons of presenting either unitsDetailed Pros and Cons of presenting either units
Detailed Pros and Cons of presenting either units
 
FUKUYAMA BASE WORKSHOP Vol13 Theme
FUKUYAMA BASE WORKSHOP Vol13 ThemeFUKUYAMA BASE WORKSHOP Vol13 Theme
FUKUYAMA BASE WORKSHOP Vol13 Theme
 
Behavioural Marketing & how to get your customers to love you
Behavioural Marketing & how to get your customers to love youBehavioural Marketing & how to get your customers to love you
Behavioural Marketing & how to get your customers to love you
 

Semelhante a Csharp generics

Advanced programming topics asma
Advanced programming topics asmaAdvanced programming topics asma
Advanced programming topics asma
AbdullahJana
 
.NET Portfolio
.NET Portfolio.NET Portfolio
.NET Portfolio
mwillmer
 
C Sharp: Basic to Intermediate Part 01
C Sharp: Basic to Intermediate Part 01C Sharp: Basic to Intermediate Part 01
C Sharp: Basic to Intermediate Part 01
Zafor Iqbal
 
classes object fgfhdfgfdgfgfgfgfdoop.pptx
classes object  fgfhdfgfdgfgfgfgfdoop.pptxclasses object  fgfhdfgfdgfgfgfgfdoop.pptx
classes object fgfhdfgfdgfgfgfgfdoop.pptx
arjun431527
 

Semelhante a Csharp generics (20)

CSharp Presentation
CSharp PresentationCSharp Presentation
CSharp Presentation
 
Synapseindia dot net development
Synapseindia dot net developmentSynapseindia dot net development
Synapseindia dot net development
 
Typescript language extension of java script
Typescript language extension of java scriptTypescript language extension of java script
Typescript language extension of java script
 
Microsoft dynamics ax 2012 development introduction part 2/3
Microsoft dynamics ax 2012 development introduction part 2/3Microsoft dynamics ax 2012 development introduction part 2/3
Microsoft dynamics ax 2012 development introduction part 2/3
 
Advanced programming topics asma
Advanced programming topics asmaAdvanced programming topics asma
Advanced programming topics asma
 
Srgoc dotnet
Srgoc dotnetSrgoc dotnet
Srgoc dotnet
 
LEARN C#
LEARN C#LEARN C#
LEARN C#
 
Ppt of c vs c#
Ppt of c vs c#Ppt of c vs c#
Ppt of c vs c#
 
Getting Started - Console Program and Problem Solving
Getting Started - Console Program and Problem SolvingGetting Started - Console Program and Problem Solving
Getting Started - Console Program and Problem Solving
 
SPF Getting Started - Console Program
SPF Getting Started - Console ProgramSPF Getting Started - Console Program
SPF Getting Started - Console Program
 
C++ language
C++ languageC++ language
C++ language
 
.NET Portfolio
.NET Portfolio.NET Portfolio
.NET Portfolio
 
C Sharp: Basic to Intermediate Part 01
C Sharp: Basic to Intermediate Part 01C Sharp: Basic to Intermediate Part 01
C Sharp: Basic to Intermediate Part 01
 
OOC MODULE1.pptx
OOC MODULE1.pptxOOC MODULE1.pptx
OOC MODULE1.pptx
 
Notes(1).pptx
Notes(1).pptxNotes(1).pptx
Notes(1).pptx
 
Java execise
Java execiseJava execise
Java execise
 
classes object fgfhdfgfdgfgfgfgfdoop.pptx
classes object  fgfhdfgfdgfgfgfgfdoop.pptxclasses object  fgfhdfgfdgfgfgfgfdoop.pptx
classes object fgfhdfgfdgfgfgfgfdoop.pptx
 
C# Unit 1 notes
C# Unit 1 notesC# Unit 1 notes
C# Unit 1 notes
 
Basics1
Basics1Basics1
Basics1
 
unit 1 (1).pptx
unit 1 (1).pptxunit 1 (1).pptx
unit 1 (1).pptx
 

Último

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Último (20)

Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 

Csharp generics

  • 1. http://www.tutorialspoint.com/csharp/csharp_generics.htm Copyright © tutorialspoint.com C# - GENERICS Generics allow you to delay the specification of the data type of programming elements in a class or a method, until it is actually used in the program. In other words, generics allow you to write a class or method that can work with any data type. You write the specifications for the class or the method, with substitute parameters for data types. When the compiler encounters a constructor for the class or a function call for the method, it generates code to handle the specific data type. A simple example would help understanding the concept: using System; using System.Collections.Generic; namespace GenericApplication { public class MyGenericArray<T> { private T[] array; public MyGenericArray(int size) { array = new T[size + 1]; } public T getItem(int index) { return array[index]; } public void setItem(int index, T value) { array[index] = value; } } class Tester { static void Main(string[] args) { //declaring an int array MyGenericArray<int> intArray = new MyGenericArray<int>(5); //setting values for (int c = 0; c < 5; c++) { intArray.setItem(c, c*5); } //retrieving the values for (int c = 0; c < 5; c++) { Console.Write(intArray.getItem(c) + " "); } Console.WriteLine(); //declaring a character array MyGenericArray<char> charArray = new MyGenericArray<char>(5); //setting values for (int c = 0; c < 5; c++) { charArray.setItem(c, (char)(c+97)); } //retrieving the values for (int c = 0; c< 5; c++) { Console.Write(charArray.getItem(c) + " "); } Console.WriteLine(); Console.ReadKey(); } }
  • 2. } When the above code is compiled and executed, it produces following result: 0 5 10 15 20 a b c d e Features of Generics Using generics is a technique that enriches your programs in the following ways: It helps you to maximize code reuse, type safety, and performance. You can create generic collection classes. The .NET Framework class library contains several new generic collection classes in the System.Collections.Generic namespace. You may use these generic collection classes instead of the collection classes in the System.Collections namespace. You can create your own generic interfaces, classes, methods, events and delegates. You may create generic classes constrained to enable access to methods on particular data types. You may get information on the types used in a generic data type at run-time by means of reflection. Generic Methods In the previous example, we have used a generic class; we can declare a generic method with a type parameter. The following program illustrates the concept: using System; using System.Collections.Generic; namespace GenericMethodAppl { class Program { static void Swap<T>(ref T lhs, ref T rhs) { T temp; temp = lhs; lhs = rhs; rhs = temp; } static void Main(string[] args) { int a, b; char c, d; a = 10; b = 20; c = 'I'; d = 'V'; //display values before swap: Console.WriteLine("Int values before calling swap:"); Console.WriteLine("a = {0}, b = {1}", a, b); Console.WriteLine("Char values before calling swap:"); Console.WriteLine("c = {0}, d = {1}", c, d); //call swap Swap<int>(ref a, ref b); Swap<char>(ref c, ref d); //display values after swap: Console.WriteLine("Int values after calling swap:"); Console.WriteLine("a = {0}, b = {1}", a, b); Console.WriteLine("Char values after calling swap:");
  • 3. Console.WriteLine("c = {0}, d = {1}", c, d); Console.ReadKey(); } } } When the above code is compiled and executed, it produces following result: Int values before calling swap: a = 10, b = 20 Char values before calling swap: c = I, d = V Int values after calling swap: a = 20, b = 10 Char values after calling swap: c = V, d = I Generic Delegates You can define a generic delegate with type parameters. For example: delegate T NumberChanger<T>(T n); The following example shows use of this delegate: using System; using System.Collections.Generic; delegate T NumberChanger<T>(T n); namespace GenericDelegateAppl { class TestDelegate { static int num = 10; public static int AddNum(int p) { num += p; return num; } public static int MultNum(int q) { num *= q; return num; } public static int getNum() { return num; } static void Main(string[] args) { //create delegate instances NumberChanger<int> nc1 = new NumberChanger<int>(AddNum); NumberChanger<int> nc2 = new NumberChanger<int>(MultNum); //calling the methods using the delegate objects nc1(25); Console.WriteLine("Value of Num: {0}", getNum()); nc2(5); Console.WriteLine("Value of Num: {0}", getNum()); Console.ReadKey(); } } } When the above code is compiled and executed, it produces following result:
  • 4. Value of Num: 35 Value of Num: 175