C# function reference to an overloaded method

185 views Asked by At

I have a static class with a few overloaded methods. I was wondering if there was a simple/elegant way of passing reference to the correct overloaded method to another method of mine.

ObjectComparer.cs:

internal static class ObjectComparer {
    internal static void AssertAreEqual(Company expected, Company actual) {
        // ...
    }

    internal static void AssertAreEqual(Contact expected, Contact actual) {
        // ...
    }
}

CollectionComparer.cs:

internal static class CollectionComparer {
    internal static void AssertAreEqual<T>(List<T> expected, List<T> actual, Action<T, T> comparer) 
    {
        Assert.AreEqual(expected.Count, actual.Count);

        for (var i = 0; i < expected.Count; i++) 
        {
            comparer(expected[i], actual[i]);
        }
    }
}

CompanyRepositoryUnitTest.cs:

[TestMethod]
public void GetAllCompaniesTest()
{
    // some work that creates 2 collections: expectedCompanies and actualCompanies

    // I am hoping I can write the following method 
    // but I am getting an error over here saying 
    // The best overloaded method ... has invalid arguments
    CollectionComparer.AssertAreEqual(expectedCompanies, actualCompanies, ObjectComparer.AssertAreEqual);
}

EDIT

It turns out the compiler was complaining about one of my other arguments: actualCompanies. It was a ICollection instead of List.

Apologies. This was a very silly mistake.

2

There are 2 answers

1
maraaaaaaaa On BEST ANSWER

I think this would also help, if your comparer is static and never changes, you might not have a need to pass it every time.

internal static class CollectionComparer {
internal static void AssertAreEqual<T>(List<T> expected, List<T> actual) 
    {
        Assert.AreEqual(expected.Count, actual.Count);

        for (var i = 0; i < expected.Count; i++) 
        {
            CollectionComparer.AssertAreEqual(expected[i], actual[i]);
        }
    }
}
5
ANewGuyInTown On

You might want to instantiate the Action as follows while passing as AssertAreEqual parameter:

var action=  new Action<Company,Company>(ObjectComparer.AssertAreEqual);
CollectionComparer.AssertAreEqual(expectedCompanies, actualCompanies, action); 

And for Contact you could simply do :

var action=  new Action<Contact,Contact>(ObjectComparer.AssertAreEqual);