C # delegates - how often do you use them and when?

Delegates look like a powerful language feature, but I still have to find an opportunity to use them in anger (except in DAL, I have to say).

How often do you use them and under what circumstances do you find them most useful?

+3
source share
9 answers

Funcs and Actions are the new "types" of delegates, and I use them a lot with Linq and really other odd situations. For Linq, they are good, because I personally prefer a descriptive name over the lambda expression:

someList.Select(item => item.Name);

Where with Func I can:

Func<Item, String> itemName = item => item.Name;
...
someList.Select(itemName);

It may be a string larger, but there are times when I find that I repeat some lambda expressions in a class several times, so personally I think Funcs work well for this.

, Factory. , Enum :

Dictionary<UserType, Action<User>> showControls;
showControls = new Dictionary<UserType, Action<User>>();

showControls.Add(SomeEnum.Admin, setControlsForAdmin);
showControls.Add(SomeEnum.Normal, setControlsForNormalUser);
showControls.Add(SomeEnum.Unregistered, setControlsForUnregisteredUser);

, - . :

showControls[user.UserType]();

, , :

Action<User> neededMethod;

neededMethod = showControls[user.UserType];

SomeMethod(neededMethod);

, , .

+3

# .

public delegate void MyDelegate(object sender, EventArgs e, string otherParameterIWant);
//...Inside the class
public event MyDelegate myEvent;
//...Inside a method
if (myEvent != null)
    myEvent(this, new EventArgs(), "Test for SO");
+6

, , . ++, , , .

+4

, :

public delegate bool ItemFilterDelegate(MyItem item);

public IEnumerable<MyItem> FilterItems(ItemFilterDelegate filter)
{
    var result = new List<MyItem>();

    foreach(MyItem item in AllItems)
    {
        if(filter(item))
            result.Add(item);
    }

    return item;
}    

public IEnumerable<MyItem> FilterByName(string name)
{
    return FilterItems(item => item.Name == name);
}

LINQ.

+3

, , .. ..

List.ForEach(...)

+1

, , # 3, , .

myList.Sort(a=> a.LastName);
+1

. ( ) .

0

, , , ( , , , ). API.

0
source

I wrote this article, maybe this will help: http://www.codeproject.com/KB/cs/Cs_delegates101_practical.aspx

0
source

All Articles