Reputation: 7440
Whats the easiest way to write overloads for methods where I dont really care in what order the user inputs the paramaters and where the type is always differently?
For example:
public void DoSomething(String str, int i, bool b, DateTime d)
{
//do something...
}
Now I would like to have the possibility that you can call the method in any possible way, for example:
DoSomething(1, DateTime.Now, "HelloWorld", false);
DoSomething(DateTime.Now, 1, "HelloWorld", false);
DoSomething("HelloWorld", DateTime.Now, 1, false);
DoSomething(false, DateTime.Now, "HelloWorld", 1);
//and so on...
Is there really no other way, than to duplicate the method over and over again and rearrange the parameters?
I specially think its annoying when you specify default values for parameters and either need to specify the name when calling the method, or set the defaults.
Upvotes: 0
Views: 90
Reputation: 44038
First of all, if your methods grow in parameters count you should seriously begin thinking about creating a specific class that can hold all this data:
public class MyData
{
public string Str {get;set;}
public int I {get;set;}
public bool B {get;set;}
public DateTime D {get;set;}
}
and have a single method signature:
public void DoSomething(MyData data)
{
//...
}
and you may use it like this:
DoSomething(new MyData {I = 1, Str = "Hello", D = DateTime.Today, B = false});
This approach has the additional advantage that it provides much more scalability, since you can add any amount of new properties into that class without having to change your method signatures at all.
Other than that, see Named Parameters.
Upvotes: 5
Reputation: 5685
You can use named parameters and specify the names of the parameters with the arguments in any order:
DoSomething(i:1, d:DateTime.Now, str:"HelloWorld", b:false);
DoSomething(d:DateTime.Now, i:1, str:"HelloWorld", b:false);
DoSomething(str:"HelloWorld", d:DateTime.Now, i:1, b:false);
DoSomething(b:false, d:DateTime.Now, str:"HelloWorld", i:1);
Or you could also use params but then you forgo type checking
Upvotes: 2
Reputation: 2857
You can use Named Parameters, take a read int his MSDN Article:
http://msdn.microsoft.com/en-us/vstudio/gg581066.aspx
Upvotes: 2