Tutorial :Function overloading vs. default parameters in VB.NET?



Question:

In VB.NET, which is better to use: function overloading or default parameters?


Solution:1

Is the code going to be used by other languages? If so, that swings the balance towards overloads while still bearing Hamish's answer in mind. In particular, C# doesn't support optional parameters - yet...

Admittedly this wouldn't actually prevent someone using your code from C#, it just might be a pain for them.

If there are a lot of parameters and they logically represent something, you might want to consider encapsulating them together, in the same way that Process works with ProcessStartInfo. That's particularly nice from C# due to object initializers.

If this is for construction, you might also consider the builder pattern as a variant of this. For instance, in Protocol Buffers I can do something like:

Person jon = new Person.Builder { Name="Jon", Age=32,                                    Spouse="Holly", Kids=3 }.Build();  

which ends up being very readable while still creating a person in one go (in one expression, and without having to mutate the person itself - indeed the message type is immutable; it's only the builder which isn't).


Solution:2

if the parameters are optional (i.e. the overloads are a subset of the parameters that the full procedure signature accepts) then default or optional parameters would make more sense.

If the overload is allowing a different type for the parameter or is a semantically different parameter that will be interpreted differently by the routine then overloads would make more sense.


Solution:3

FYI

If you want to add a parameter to a function or method that is called from other assemblies, then:

You can overload by making an additional function with the extra parameter.

Or you can add an optional parameter, BUT: You have to recompile all of the assemblies that call this function, even if they don't need to use the new optional parameter! This is not usually what people expect (expecially those used to how VB6 works). Basically, you can't slip in a new optional parameter to a function and expect it to be totally backwards compatible. Also, as I understand it, if you change what the default value is, you need to rebuild all calling assemblies for the change to work.


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