Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Usage of named parameters

Tags:

c#-4.0

Sorry, if duplicate.

I'm reading CLR via C#. Chapter "Parameters" starts with the explanation of optional and named parameters.

So, can you give some example where using of named parameters has some benefits, or is it just the matter of style or habit? Do you personally use named parameters?

like image 775
26071986 Avatar asked Dec 03 '22 11:12

26071986


2 Answers

Named parameters are very useful when combined with optional parameters in C# 4. This allows you to avoid providing a lot of method overloads, and instead just have a single one.

For example, instead of having 5 versions of a method, you can provide one method with multiple optional parameters, then call it as:

this.Foo("required argument", bar: 42);

This can simplify an API (one method instead of many), and still provide the same flexibility, without requiring the user to type in every argument. Without this, you'd either need many overloads, or have to provide all of the default values.

like image 161
Reed Copsey Avatar answered Apr 11 '23 06:04

Reed Copsey


Besides being used with optional parameters, named parameters are sometimes useful to make code more readable.

For example:

DrawLine(10, 10, 25, 16);

If you're not familiar with this (fictional) DrawLine method, but you know the box needs to be a little taller, you'd have to look up the method to determine which parameter to change. (Is it "Left, Top, Right, Bottom" or "Top, Left, Bottom, Right" or "Top, Height, Left, Width" etc.)

But:

DrawLine(left: 10, top: 10, width: 25, height: 16); 

This makes clear exactly what is intended and which parameter to adjust.

like image 24
Jason Avatar answered Apr 11 '23 08:04

Jason