RoboJ1M
RoboJ1M

Reputation: 1640

How can I make this C# method more generic?

I have this method:

public partial class Client : ConfigItem
{
    public void ValidateForInsert(ASystem defaultSystem, IEnumerable<Client> currentConfig)
    {
        if (this.Source == defaultSystem.SystemName)
        {
            throw new InvalidOperationException(AMessage);
        }
        if (SomeOtherValidation())
        {
            throw new InvalidOperationException(AnOtherMessage);
        }
    }
}

It's going to exist on many different types, all of which inherit from CofigItem

All the code is identical, so I want to move it to the base class. Except the parameters contain IEnumerable<ThisClassesType> currentConfig

If I put it in the base class with IEnumerable<ConfigItem>, I have to call it with:

client.ValidateOnInsert(defaultSystem, currentConfig.Cast<ConfigItem>());

Which seems a bit daft as types of things like client will always be based off of ConfigItem.

Is there anyway to put something like:

public void ValidateOnInsert(ASystem system, IEnumerable<T> currentConfig) where T : ConfigItem(?)

Or just any way of making that neat, tidy and not require duplicate code or lots of casting?

Thanks,

J1M

Upvotes: 1

Views: 100

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1503839

It's not clear whether or not this will work as you haven't shown any code using the input sequence, but this may work:

public void ValidateForInsert<T>(ASystem defaultSystem,
                                 IEnumerable<T> currentConfig)
    where T : ConfigItem

So that's a generic method taking a sequence of items of type T, where T must be ConfigItem or some type derived from it.

Upvotes: 1

Related Questions