Click here to Skip to main content
15,912,400 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have a Method with 5 arguments:
Method(arg1, arg2, arg3, arg4, arg5);

In a situation I have to use same method with 3 arguments
Method(arg2, arg3, arg5);

Optional Parameter is something I found! But, here other arguments have no defaults.

C# Corner : Error Display[^]

Do we have any other ways in C# for situations like this.
Please, ignore if this is a stupid question and my knowledge is way worse to discuss.

Thanks!
Posted

Optional parameters have to be the last parameters in the signature. Put differently: All parameters after the first optional parameter have to be optional as well. So in your given example you would have to move the parameters 1 and 4 to the end of the signature of the method in order to be able to call it with arg2, arg3, arg5 only:
C#
void Method(int arg2, int arg3, int arg5, int arg1=0, int arg4=0)
(Where the default values of 0 can be different of course.)

Somewhat related, though not a solution here, is the named argument syntax. If you declared all of your parameters as optional, you could call the method like this:
C#
Method(arg2: 1, arg3: 2, arg5: 3);


For further reading, take a look here: Named and Optional Arguments[^]

Edit: Addendum to named arguments: You could use them for method calls that have or have none optional parameters. Just like with optional parameters, those arguments following the first named argument also have to be named.
Most often named arguments are used to be able to skip optional parameters: Without named arguments, if you wanted to provide a value for, say, the second optional parameter of a method, you would have to specify a value for the first one, too. Named arguments allow you to provide values only for those optional parameters that you want to.
 
Share this answer
 
v2
Comments
Sergey Alexandrovich Kryukov 29-Jan-16 14:45pm    
5ed, by I think the explanation of the older approach is also important.
Also, you probably should have explained the relationships between optional and named parameters (as opposed to positional) — the order of real arguments at the call can be different. Those are related by different features; and named feature is very important.
Please see Solution 2 in addition to your Solution 1.
—SA
Sascha Lefèvre 29-Jan-16 14:59pm    
Of course! I meant to add it.. slipped somehow :) Thank you, Sergey.
Cyrus_Vivek 29-Jan-16 22:09pm    
+5. Solution.
Thanks. Helped me understanding the scenario. I will try to use this in my code.
-Cyrus
In addition to Solution 1.

There are two alternatives. The optional parameters feature has been added to C# later, and before it happened, there was the older opportunity, related to the fact that it's allowed to have more than one method under the same name. Usually it's called by quite a confusing term "method overloading". (Yes, many beginners have been badly confused and asked questions on this forum.) So, alternatively, you could write:
C#
void Method(int first, int second) { /* ... */ }
void Method(int first) {
   Method(first, 0); // 0 is the same very default value for "second" here
   // use also the parameter "first" now
   // ...
}
I would say that the newer approach based on optional parameters is better, more explicit, but some prefer the older style described above. Some do it because they use VS 2008 (with the latest target of .NET v.3.5) or earlier.

Note that always there are cases where the code at the call is ambiguous, then using exact types helps, say, using explicitly typed variable/members/constants instead of immediate constants, such as 0.

As to the newer approach, it's important to understand that the arguments with default values can be not only optional but also named, which is event better feature. The named mechanism is opposed to the positional one; the order of arguments at call may vary. Please see: Named and Optional Arguments (C# Programming Guide)[^].

—SA
 
Share this answer
 
v7
Comments
Sascha Lefèvre 29-Jan-16 15:12pm    
+5
Sergey Alexandrovich Kryukov 29-Jan-16 16:07pm    
Thank you, Sascha.
—SA
Cyrus_Vivek 29-Jan-16 22:07pm    
+5. Solution
Thanks a lot. thank you for showing the alternatives. This will surely help. I marked both as solved as both did help me understand!
Sergey Alexandrovich Kryukov 29-Jan-16 22:14pm    
You are very welcome.
Good luck, call again.
—SA
What to do ?

When trying to decide whether to use optional parameters, or define multiple methods with the same name, but different parameter lists (method overloading): consider optional parameters in one method definition when it doesn't matter if that optional parameter has a value defined ... in other words, the code that executes is the same. However, if you have methods that use different Types of parameters, use method overloading. See: [^].

What not to do ?

A potential problem with optional parameters is that certain Types used as parameters will be auto-initialized to non-null values, and you may have trouble distinguishing whether the caller passed you a valid value, or not.

For example:

private void MyMethod(int int1, string string1 = "", int int2 = 0)

In the body of this method, how will you know if the values of 'string1, and 'int1 have been explicitly set by the caller, rather than having been set by default ? That can lead to quirky code work-arounds like this:
C#
private void MyMethod(int int1, string string1 = null, int? int2 = null)
{
    Console.WriteLine("{0}, {1}, {2}", int1, string1, int2);

    if(string1 != null) // do something with 'string1

    if(int2 != null) // do something with 'int2
}
Where you take advantage of the fact that Type 'String can be 'null, and you use a nullable-Int parameter to allow the integer entry to be null. I consider this a "code-smell."

Another strategy, if all your parameters are the same Type, is to use the 'params keyword to allow a variable length Array of parameters:
C#
private void MyMethodWithVariableParams(params int[] intParams)
{
    foreach(int theInt in intParams)
    {
        // do something with 'theInt
    }
}
This is most useful when you really want to iterate over the parameter Array. It is less useful, when you have to write if/else statements, or a switch statement, to handle different lengths of the parameter Array.

In my opinion, I think it best to minimize use of optional parameters, but, if you do, you can take advantage of how the calling syntax that uses Named Parameters allows you to skip parameters you don't want to set in a given method call.

I find it "unfortunate" that many people refer to "Named Parameters" as if they were another type of parameter that can be used in declaring a Method, when, in fact, this is only an optional syntax for calling a Method.

An interesting essay on possible drawbacks of using optional arguments: [^].

I prefer to see method-overloading when there are distinct parameter-configurations that will be called frequently ... as long as: code common to all method-overloads is factored out into a separate method.

If you are using .NET 4.0 or later, and you really want to make your code smell good, you can use the 'OptionalParameter Attribute:
using System.Runtime.InteropServices;

private void MyMethod(int int1, [OptionalParameter] string1, [OptionalParameter] int2)
{
    // whatever
}
To use this attribute, you must reference the System.Runtime.InteropServices library: however, the variables will be initialized in the same way that optional variables defined without the Attribute are. Using this Attribute has no run-time performance penalty.
 
Share this answer
 
v4
Comments
Cyrus_Vivek 31-Jan-16 0:57am    
+5 Nice.
I will surely keep this in mind Bill.
Thanks - Cyrus
Cyrus_Vivek 31-Jan-16 1:01am    
Bill, can you resend Method Overloading link you posted.
Whatever reason, the link you provided is not working for me.
I appreciate that you are providing valuable information even after marking answered!
Thanks - Cyrus.
BillWoodruff 8-Feb-16 12:40pm    
Hi, I thought the link was to an article by Jon Skeet, but I can't seem to locate it in my bookmarks. However, this article does give a good overview of "method overloading" clearly indicating why this is a form of "polymorphism."

Another reason to use method-overloading is because there is no run-time "negotation" by the compiler to determine which method to call, as there can be with optional parameters:

http://haacked.com/archive/2010/08/10/versioning-issues-with-optional-arguments.aspx/

cheers, Bill

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900