简体   繁体   中英

C# defining one method for different types of argument

I've seen that you can define different functions for different sets of arguments in c#, like so:

public bool foo(string bar) {
    //do something1
}
public bool foo(int bar, bool spam) {
    //do something2
}

But can you make a single function definition for different sets of arguments? In my case, it'll be for IList and List . Since those types are only slightly varied I can use the same function for both IList and List objects (it's a simple function that just looks for some specific element). Is there any clever way of doing this, as in not a copypasta?

Thanks!

Yeah, you could use only IList as the type of your parameter, since List implements IList .

For instance, you could declare

public void MethodName(IList list)
{
    // Method's body.
}

and the list you will pass could be either a concrete List or a type that implements IList , without having to declare two mehods.

Well if you are trying to use IList and List . I don't think you need different methods for that. Because List implements IList and thus you can easily cast them in your code. So the same functions will work for both.

And if you are not modifying the items in the function then you can go little further and use IEnumerable as the parameter type.

such as -

protected void Method(IList list){

}

or

protected void Method(IEnumerable items){
}

But remember, there is a difference when using interfaces, they are passed by references and thus no new copy is created. Any modification you make will affect the original item collection. If you need to pass by value or want to create a new copy call .ToList() inside -

such as -

protected void Method(IList list){
    //some code
    var copied = list.ToList();
}

or

protected void Method(IEnumerable items){
    //some code
    var copied = items.ToList();
}

List object internally inherited by IList. So use when you call method then convert IList to List object or List object to IList what ever you use object type in method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM