n00dles
n00dles

Reputation: 256

How do I refactor two methods with very similar list types into a generic method?

I have two methods which are very similar. The only difference is the type used in the BindingList, but I can't work out how to create a generic method for both types. I think I have to use generic types to get it to work, but I can't figure it out. Both the types have a Title property.

private int GetObjectIndexFromTitle(string str, BindingList<MyClass1> list)
{
    foreach (var item in list)
    {
        if (item.Title == str)
        {
            return list.IndexOf(item);
        }
    }
    return -1;
}

And this:

private int GetObjectIndexFromTitle(string str, BindingList<MyClass2> list)
{
    foreach (var item in list)
    {
        if (item.Title == str)
        {
            return list.IndexOf(item);
        }
    }
    return -1;
}

I've looked through the Generic Type documentation, but I couldn't get it to work because of the very specific Title property. I would love some help with this.

Upvotes: 0

Views: 103

Answers (2)

Ottak
Ottak

Reputation: 293

   public static class myClass
    {
        public static int GetObjectIndexFromTitle<T>(T myList, string myString)
        {
            foreach (var item in myList)
            {
                if (item.Title == myString)
                {
                    return list.IndexOf(item);
                }
            }
            return -1;
        }
    }

Usage:

myClass.GetObjectIndexFromTitle<myClass1>(myList1, "myString1");
myClass.GetObjectIndexFromTitle<myClass222>(myList2222, "myString222");

Upvotes: -2

gaheinrichs
gaheinrichs

Reputation: 610

Create an interface with:

public interface ITitleAware{
   string Title { get; } 
}

Your classes will implement it:

public MyClass1 : ITitleAware {
   //code
}

public MyClass2 : ITitleAware {
   //code
}

Then:

private int GetObjectIndexFromTitle(string str, BindingList<ITitleAware> list)
{
    foreach (var item in list)
    {
        if (item.Title == str)
        {
            return list.IndexOf(item);
        }
    }
    return -1;
}

Upvotes: 5

Related Questions