Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a method as an argument

Tags:

c#

delegates

I have a method SaveChanges<T>(T object) that is frequently called throughout my code, except depending on the action calling the method, there would be a different method called from within SaveChanges. Something like this...

protected void SaveChanges<T>(T mlaObject, SomeFunction(arg))
    where T : WebObject
{
    try { this._db.SaveChanges(); }
    catch (Exception e)
    {
        Console.WriteLine("Error: " + e);
        SomeFunction(arg);
    }
}

Usage Examples:

SaveChanges<MlaArticle>(article, article.Authors.Remove(person)) //person is an object of type MlaPerson
//OR
SaveChanges<MlaArticle>(article, article.RelatedTags.Remove(tag)) //tag is an object of type Tag
//OR
SaveChanges<MlaArticle>(article, article.RelatedWebObjects.Remove(location)) //location is an object of type MlaLocation

I've read up on delegate methods but I'm a little confused as to how to implement this with my requirements or if my requirements warrant use for delegates at all.

EDIT: Also, would it be possible to pass multiple Actions?

like image 976
bflemi3 Avatar asked Oct 10 '11 14:10

bflemi3


1 Answers

How about:

protected void SaveChanges<T>(T mlaObject, Action<T> rollback)
    where T : WebObject
{
    try { this._db.SaveChanges(); }
    catch (Exception e)
    {
        Console.WriteLine("Error: " + e);
        rollback(mlaObject);
    }
}

Called like:

this.SaveChanges(myObj, x => article.Authors.Remove(x));

Now, from a second read of your question, I don't see a point in passing the mlaObject as it is never used.

// this.SaveChanges(
//     () => article.Authors.Remove(author),
//     () => article.RelatedTags.Remove(tag));
protected void SaveChanges(params Action[] rollbacks)
{
    try { this._db.SaveChanges(); }
    catch (Exception e)
    {
        Console.WriteLine("Error: " + e);
        foreach (var rollback in rollbacks) rollback();
    }
}

// Overload to support rollback with an argument
// this.SaveChanges(
//     author,
//     article.Authors.Remove,
//     authorCache.Remove);
protected void SaveChanges<T>(T arg, params Action<T>[] rollbacks)
{
    try { this._db.SaveChanges(); }
    catch (Exception e)
    {
        Console.WriteLine("Error: " + e);
        foreach (var rollback in rollbacks) rollback(arg);
    }
}
like image 167
user7116 Avatar answered Sep 29 '22 02:09

user7116