C # function reference to overloaded method

I have a static class with several overloaded methods. I was wondering if there was a simple / elegant way to pass the reference to the correct overloaded method to another method.

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 ICollection instead of List.

I'm sorry. It was a very stupid mistake.

+3


source to share


2 answers


I think it would also help if your comparator is static and will never change, you may not 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]);
        }
    }
}

      

+1


source


You might want to instantiate Action

like below as a parameter AssertAreEqual

:

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

      



And for Contact

you can simply do:

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

      

+1


source







All Articles