OVERLOADING

A

AA2e72E

Why use overloading?

I have used it to allow for optional arguments.

It is also possible to use overloading to cater for arguments of different
types, I believe. E.G.

public string mymethod(string myarg)
{
}

public string mymethod(string[] myarg)
{
}

What are the implications of using overloading to cater for arguments of
different types?

Thanks for your help.
 
J

Jon Skeet [C# MVP]

Why use overloading?

It allows you to reuse a name for many different signatures, which can
increase consistency. Look at Convert.ToInt32 for example - loads of
different overloads. Why would you want to have to specify a different
name for each of those overloads?
I have used it to allow for optional arguments.

Yes, that's a common use.
It is also possible to use overloading to cater for arguments of different
types, I believe. E.G.

public string mymethod(string myarg)
{

}

public string mymethod(string[] myarg)
{

}

What are the implications of using overloading to cater for arguments of
different types?

It's generally okay, *but* you can get into difficulties if there's
any ambiguity. For instance:

public string MyMethod(string x)
....
public string MyMethod(object o)

A string argument is valid for both methods. The C# language spec
specifies how overloads are resolved, but it can get quite hairy,
particularly when inheritance is involved.

If the types are completely distinct (i.e. there are no conversions
between them - e.g. string and float) then there's less of an issue.

Jon
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top