Charlie
Charlie

Reputation: 10307

Optional parameters

I've got a method that takes a bunch of optional parameters and I'm overloading the method to supply the different combinations of signatures. Intellisense pops up with a bunch of different signatures but I think it looks quite confusing now because there are different combinations I need to provide, not just building up parameters on the end of the method signature.

Should I just not overload my method and stick to one signature so that the user of my method has to pass in nulls? It would make the signature clearer but makes the calling code look messier.

Upvotes: 1

Views: 456

Answers (3)

SwDevMan81
SwDevMan81

Reputation: 50018

You could use the params keyword if the function definitions only vary in length (and not order, otherwise this wont be the best approach).Then in the function you can setup the values you need based on the parameter input

Upvotes: 0

KV Prajapati
KV Prajapati

Reputation: 94653

Think about params argument of c# method.

void test(params object []arg) {
   ..
}

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1503180

Are you restricted to using C# 1-3? C# 4 supports optional parameters and named arguments...

Until then, you should probably either stick with overloading or create a separate class with mutable properties, e.g.

FooOptions options = new FooOptions { Name="Jon", Location="Reading" };
Foo foo = new Foo(options);

That can all be done in one statement if you want... and if some of the properties are mandatory, then create a single constructor in FooOptions which takes all of them.

In C# 4 you'd be able to write:

Foo foo = new Foo(name: "Jon", location: "Reading");

if the constructor was written as

public Foo(string name,
           int age = 0,
           string location = null,
           string profession = null)

Named arguments and optional parameters should make it a lot easier to construct immutable types with optional properties in C# 4 :)

Upvotes: 8

Related Questions