In Visual Basic, default values are assigned for:
Optional keyword and initializer.Public Sub LogMessage(message As String, Optional level As String = "INFO") Console.WriteLine($"[{level}]: {message}") End Sub ' Call without the second argument - will be 'INFO' LogMessage("Test")
Public Property Status As String = "Undefined"
Features:
Can you set a default value for a parameter of object type (for example, a class) in VB.NET?
Answer: No, only constant expressions are allowed for Optional parameters, meaning only value types and strings. For objects, you can only use the value Nothing, and if you need an object, it should be created in the method body:
Public Sub DoWork(Optional obj As SomeClass = Nothing) If obj Is Nothing Then obj = New SomeClass() End If ' ... End Sub
Story
Financial System: When adding a new parameter with an Optional value, the developer did not specify it at the end of the list. The entire call compiled, but the parameters shifted, which led to incorrect value passing.
Story
Reporting System: Used properties with auto-initialization (VB.NET 2010+), but forgot to account for the logic of overriding values from the construct, causing the default value to be overwritten incorrectly.
Story
Integration with external API: In an attempt to set an object as a default value for an Optional parameter, a compile-time error occurred, which delayed the release and required extensive refactoring of method signatures.