Tutorial :Optional parameters



Question:

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.


Solution:1

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 :)


Solution:2

Think about params argument of c# method.

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


Solution:3

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


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »