-2

If I have two methods in the same class of the same name, do the parameters help to differentiate the methods from each other to avoid conflict?

i.e.

Class1
{
    void CompareInput(Form1 frm) { }

    void CompareInput(Form2 frm) { }
}
Ben
  • 2,433
  • 5
  • 39
  • 69
  • 1
    They do - but your question makes no sense since one of the important factors in _function overloads_ is that the types are different. You've provided none. – Simon Whitehead Aug 20 '14 at 00:09
  • this link should clear any questions - http://csharpindepth.com/Articles/General/Overloading.aspx – terrybozzio Aug 20 '14 at 00:34

2 Answers2

2

Yes, it is called Overloading:

interface ITest
{
    void F();                     // F()
    void F(int x);                // F(int)
    void F(ref int x);            // F(ref int)
    ...
    int F(string s);              // F(string)
    ...
}

The idea is that the compiler picks up the right function basing on the types of its arguments.

For instance, the following code would call two different functions:

ITest test = // get interface
test.F(0);
test.F("string");
AlexD
  • 32,156
  • 3
  • 71
  • 65
  • "the compiler *may* pick up the right one". This says to me there's a possibility something could go wrong... Is that right? – Ben Aug 20 '14 at 00:22
  • @Ben I changed wording. The compiler should pick up the right function or complain. If you have `f(string)` and `f(int)`, it is easy and intuitive. But some cases it might be more confusing, see e.g. http://stackoverflow.com/q/18310196. – AlexD Aug 20 '14 at 00:45
2

Yes. The differentiation is done by the types of the parameters and is called Member Overloading (aka Method Overloading):

A member's signature includes its name and parameter list. Each member signature must be unique within the type. Members can have the same name as long as their parameter lists differ. When two or more members in a type are the same kind of member (method, property, constructor, and so on) and have the same name and different parameter lists, the member is said to be overloaded ..

The actual method to use is chosen based upon the parameter list types and the type of the arguments applied at the call/usage-site.

In general the "best" selection is chosen, and examples can be found readily (eg. Overloaded method selection logic) for specific cases. If no matching signature is found a compiler error will be raised.

Community
  • 1
  • 1
user2864740
  • 60,010
  • 15
  • 145
  • 220