It is my understanding that it is not possible to have an optional parameter in a delegate in the version of VB that ships with VS2008.
However, I am wondering if there are any workarounds or plans for incorporating this feature into VB.NET in the future?
What I’d like to do:
Public Delegate Function Deserializer(Of T)(ByRef Buffer() As Byte, optional ByRef BufferPosition As Integer = 0) As T
'Implementation of a func that matches the delegate'
Class A
Public Function Deserialize(Byref Buffer() as Byte, optional Byref BufferPosition as integer = 0)
....
In the absence of specifying “optional” inside the actual delegate itself, it’d at least be nice to be able to do it in the function implementation only:
Public Delegate Function Deserializer(Of T)(ByRef Buffer() As Byte, ByRef BufferPosition As Integer) As T
'Implementation of a func that matches the delegate'
Class A
Public Function Deserialize(Byref Buffer() as Byte, optional Byref BufferPosition as integer = 0)
....
At least this second way, the functions for the delegate will always have a value mapped to each parameter, although some may come from the function side and not the calling side.
Instead of trying to write a delegate signature that handles all the cases I am interested in, and possibly limiting future flexibility (though it really depends on the case..), I sometimes use an Action (delegate who’s signature takes no parameters) instead of writing my own delegate:
There is a feature in C# (and I’m pretty sure in VB) that allows you to include values from the local scope, rather than passing them as parameters. It is called an anonymous delegate. In general CS terms, taking local values with you, rather than passing them as a parameter, is one form of what is called a closure.
Then, SomeFunction doesn’t need to know what parameters apply to the specific action.
More info about Action: (the answer is about closures, but this may be helpful too)
Action is simply a delegate that takes zero parameters, and returns zero values:
http://msdn.microsoft.com/en-us/library/system.action.aspx
Just like any other delegate, you can also use Action as a member variable.
There are more pre-designed delegates:
etc.