Reputation: 2000
I have the following situation:
A constructor takes 6 values. Some of them have default values, some not.
#pseudocode# Foo(int a, int b=2, int c=3, int d=4, int e=5, int f){}
And I want to be able to call all possible combinations without having to write always all 6 parameters.
#pseudocode# Foo f1 = new Foo(a=1, d=7, f=6);
#pseudocode# Foo f2 = new Foo(a=1, b=9, d=7, f=6);
Besides doing this with method overloading (which would be tedious), is there a more elegant solution?
Upvotes: 5
Views: 229
Reputation: 9318
in C# 4, there are named parameters see Named and Optional Arguments (C# Programming Guide)
which would result in
new Foo(a: 1, d: 7, f: 6);
Another solution wwould be to define a Constructor with your defaut value ans use Object Initializer to set the values How to: Initialize Objects by Using an Object Initializer (C# Programming Guide)
new Foo()
{
a = 1,
d = 7,
f = 6
};
Upvotes: 12
Reputation: 38397
2 things:
1) default parameters are left to right, once you start defaulting parameters you cannot have a non-defaulted after it, so f
must have a default (in your example)
2) you can use parameter naming to skip over a default parameter:
var f1 = new Foo(5, 9, e: 9, f: 10);
This gives a =5, b = 9, c = the default, d = default, e = default, f = 10
Provided you are using C# 4.0 compiler of course...
Upvotes: 0
Reputation: 11495
I would prefer refactoring to a Parameter Object. Something like:
Foo f1 = new Foo (new FooParameters () { B = 7 })
And your FooParamaters class can encapsulate the defaults:
public class FooParameters
{
public int A { get; set; }
public int B { get; set; }
public FooParameters ()
{
A = 1;
B = 2;
}
}
Upvotes: 1
Reputation: 40325
use the following for naming arguments:
Foo f1 = new Foo(a: 1, d: 7, f: 6);
Foo f2 = new Foo(a: 1, b: 9, d: 7, f: 6);
More information on Named and Optional Arguments avalable here:
http://msdn.microsoft.com/en-us/library/dd264739.aspx#Y515
Upvotes: 1