Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can method overloading be avoided?

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?

like image 204
Fabian Avatar asked Jul 11 '11 20:07

Fabian


1 Answers

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
};
like image 112
moi_meme Avatar answered Sep 30 '22 20:09

moi_meme