Chapter123:Funcdelegates

No Comments

Parameter                                Details

argor arg1the (first) parameter of the method arg2                      

   thesecondparameterofthemethod

arg3                  the third parameter of the method

arg4                  the fourth parameter of the method

Tor T1              the type of the (first) parameter of the method

T2                         thetypeofthesecondparameterofthemethod T3                      

   the type of the third parameter of the method

T4                         the type of the fourth parameter of the method

TResult             the return type of the method

Section123.1:Withoutparameters

Thisexampleshowshowtocreateadelegatethatencapsulatesthemethodthatreturnsthecurrenttime

staticDateTimeUTCNow()

{

returnDateTime.UtcNow;

}

staticDateTimeLocalNow()

{

returnDateTime.Now;

}

staticvoidMain(string[]args)

{

Func<DateTime>method=UTCNow;

//methodpointstotheUTCNowmethod

//thatretunscurrentUTCtime

DateTimeutcNow=method();

method=LocalNow;

//nowmethodpointstotheLocalNowmethod

//thatreturnslocaltime

DateTimelocalNow=method();

}

Section123.2:Withmultiplevariables

staticintSum(inta,intb)

{

returna+b;

}

staticintMultiplication(inta,intb)

{

returna*b;

}

staticvoidMain(string[]args)

{

Func<int,int,int>method=Sum;

//methodpointstotheSummethod

//thatretuns1intvariableandtakes2intvariables

intsum=method(1,1);

method=Multiplication;

//nowmethodpointstotheMultiplicationmethod

intmultiplication=method(1,1);

}

Section123.3:Lambda&anonymousmethods

Ananonymousmethodcanbeassignedwhereveradelegateisexpected:

Func<int,int>square=delegate(intx){returnx*x;}

Lambdaexpressionscanbeusedtoexpressthesamething:

Func<int,int>square=x=>x*x;

Ineithercase,wecannowinvokethemethodstoredinsidesquarelikethis:

varsq=square.Invoke(2);

Orasashorthand:

varsq=square(2);

Notice that for the assignment to be type-safe, the parameter

types and return type of the anonymous method must match those of the delegate type:

Func<int,int>sum=delegate(intx,inty){returnx+y;}//error

Func<int,int>sum=(x,y)=>x+y;//error

Section123.4: Covariant & ContravariantType Parameters

FuncalsosupportsCovariant&Contravariant

//Simplehierarchyofclasses.

publicclassPerson{}

publicclassEmployee:Person{}

classProgram

{

staticEmployeeFindByTitle(Stringtitle)

{

//Thisisastubforamethodthatreturns

//anemployeethathasthespecifiedtitle.

returnnewEmployee();

}

staticvoidTest()

{

//Createaninstanceofthedelegatewithoutusingvariance.

Func<String,Employee>findEmployee=FindByTitle;

//ThedelegateexpectsamethodtoreturnPerson,

//butyoucanassignitamethodthatreturnsEmployee.

Func<String,Person>findPerson=FindByTitle;

//Youcanalsoassignadelegate

//thatreturnsamorederivedtype

//toadelegatethatreturnsalessderivedtype.

findPerson=findEmployee;

}

}

About us and this blog

We are a digital marketing company with a focus on helping our customers achieve great results across several key areas.

Request a free quote

We offer professional SEO services that help websites increase their organic search score drastically in order to compete for the highest rankings even when it comes to highly competitive keywords.

Subscribe to our newsletter!

More from our blog

See all posts

Leave a Comment