I come from an Objective-C background, and I’m writing some VB.NET that includes a delegate. I have a class Worker that performs some task. One of the properties of this class is an ILogger object, which has a method for appending to some log file. (I want my Worker object to be decoupled from the logging, which will be handled by my GUI.) In Objective-C I could just declare
@property (nonatomic, strong) id<LoggingDelegate> logger;
and then sprinkle my code with lines like
[logger appendToLog:@"Beginning polarity reversal..."];
In Objective-C, logger doesn’t actually need to be set to an object for this to work; if it’s a null reference (“nil” in Objective-C), the appendToLog: message is silently ignored by the runtime.
In VB.NET I can do something similar:
Public Property logger As ILogger
and
logger.AppendText("Beginning polarity reversal...")
But of course, logger actually needs to be set to an object for this to work. What’s the idiomatic way to handle the case that I don’t have a logger object attached to my worker? (More generally, is my implementation of the delegate pattern idiomatic in VB.NET?)
Every time you use the optional object, you could check if it’s null first, for instance:
Or, you could create a private method that does the extra check for you:
Or, as vcsjones recommended, you could default the property to a dummy object:
Or, the closest thing to an “optional delegate” in VB.NET is actually an
Event:Update
As of VB 14.0 (Visual Studio 2015), you can now use the
?.operator (it’s called the “null conditional” operator):Or, if you want to use an actual delegate, you can use the same operator with delegates too. So, if you have a delegate variable called
appendToLog, you could call: