optional parameters, overloaded methods or properties [duplicate]
Possible Duplicate:
Should you declare methods using overloads or optional parameters in C# 4.0?
Hi have a method that is increasingly getting more parameters. The thing is that most of these parameters are optional as they will only affect the method in certain cases and are not needed for most instances that the method is called.
Now the question is should i use
Optional parameters
public object MyMethod(string param1, string param2, string optionalParam = null)
Overloaded methods
public object MyMethod(string param1, string param2, null)
public object MyMethod(string param1, string param2, string optionalParam)
Properties
开发者_开发问答
Suggestions welcome
I would suggest definitely oveloaded methods, as their TypeSafe not like parameters {objects}, and as quantity of parameters increases you should have control on length of parameters arrays Length and all that mess. Never like that approach, so I'm, definitely, for overloading. Regards.
I like to use Overloaded methods rather than Optional Parameters because:
- It's prettier
- You can use intellisense to document the use of each of your different overloads
- Unless your method could possibly require all those optional parameters at the same time, you wont' end up with a method name the length of the Nile.
Now, as to the use of properties... I generally tend to use those if:
- More than one method will need the data in these variables and/or
- More than one place OUTSIDE your class containing the method will need to access/call these variables.
IMHO.
How many parameters do you have? If I start to get a lot of parameters, and they are related, I generally wrap them up in to a class and use that as a single parameter to the method. It saves having a load of overloads and complicated signatures. I'm sure there will be people who disagree with this method but I find it often improves the readability of the code.
you can also create a class that holds the parameters properties
class Params
{
public string param1 { get; set; }
public string param2 { get; set; }
}
public void MyMethod(Params param) { ....}
However, I feel that you may rethink your application... (but I don't know the requirement of your application)
In this case, you should use optional parameters.
If the parameters and/or parameter types of the function or the return type differs, you should use overloading.
精彩评论