Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - delegate System.Func< >

Tags:

c#

How to use delegate System.Func< >? Shall we control the execution order of funcion or events using it?

simple example would be helpful

like image 231
user160677 Avatar asked Aug 21 '09 19:08

user160677


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr. Stroustroupe.

Is C language easy?

C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.

How old is the letter C?

The letter c was applied by French orthographists in the 12th century to represent the sound ts in English, and this sound developed into the simpler sibilant s.


1 Answers

Suppose you have a function such as:

private static string toLower(string s)
{
    return s.ToLower();
}

There is a version of System.Func that takes two generic arguments, the first being the type of the first parameter, the second being the return type. As such, you could write:

Func<string,string> myFunction = toLower;
string s = myFunction("AsDf"); 
// s is now "asdf"

In all versions of System.Func, the last generic argument is the return type, all the others are the types of the parameters, in order.

System.Func is usefull because it does not require you to write custom delegate types. This makes it much easier to interop delegates with the same signature.

Say I had:

public delegate string MyDelegate1(string s);
public delegate string MyDelegate2(string s);

MyDelegate1 myDel = new MyDelegate1(toLower); // toLower as above

There is now no way to conver my MyDelegate1 delegate to an object of type MyDelegate2, even though they have the same method signature. On the other hand, if we had used Func instead of declaring a custom delegate type, we wouldn't have this problem

like image 136
LorenVS Avatar answered Oct 01 '22 14:10

LorenVS