Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Optioan Arguments in C#

Status
Not open for further replies.

fid

Programmer
May 10, 2001
20
US
How do i write a function that will accept optional arguments?

ie: so the function can be called
_obj.DoSomething(arg1, arg2, arg3);
or
_obj.DoSomething(arg1);
or simply as
_obj.DoSomething();

how do i set up
public string DoSomething(int arg1, int arg2, int arg3)
etc... without getting the "invalid number of arguments" error ??

thanks in advance

fid
 
Hi!

It’s simple when you know how to do it. So I will try to explain how it's done.
The thing you are talking about is called function overloading. It gives the possibility to have different versions of the same function.
You have to have different function signatures so that the compiler can understand which function overload to use. A function signature is the parameter list, for example (int a, int b). This signature is different with this: (int a, string b), they have the same number of arguments, but they are different types.
Here is a short example:

public class SomeClass
{

public int SomeFunction(int a)
{
return a*a;
}

public int SomeFunction(int a, int b)
{
return a*b;
}

public int SomeFunction(int a, int b, int c)
{
return a*b*c;
}

//This overload doesn't work, the signature is
//the same as in the first function.
public void SomeFunction(int a)
{
Console.WriteLine (a);
}

public void SomeFunction (int a, string b)
{
Console.WriteLine("a is {0} and b is {1}",
a, b);
}
}

I hope that this clear things up. The chapter 7.4 in the C# Language specification has more info.

Markus Larsson
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top