"Optional" parameters, when to overload and when to use a nullable type?
Since making a type nullable essentially makes the variable "optional", I'm wondering whe开发者_Go百科n it's appropriate to use nullable types in method parameters in order to make them optional when using an overload could accomplish the same thing?
I wouldn't - you'll end up with a lot of null, null, null
. In C# 4.0 you have optional parameters and named arguments; wait a few more months and consider using them. Until then, overloads, or pass it objects that represent the args:
SearchOptions options = new SearchOptions {
Key = 123, Name = "abc"
// but 27 other properties we **haven't** set
}
Search(options);
You would still have to explicitly include a null as a parameter so it's not really optional. It's just annoying, overloading is by far the best approach imo.
I've created some methods that interact with a database where it is just easier to use a nullable type. If you have a stored procedure to which you're passing arguments, the code will look almost the same if you had two overloaded versions of an insert method, for example. Using nullable types allows you to avoid repeating yourself across the overloads.
Edit: If you prefer to use overloading and still want to not repeat code, you could also have an internal function do the work and use the overloads for the public methods.
精彩评论