How to write [DefaultValue (null)] in VB.NET? <DefaultValue (Nothing)> does not compile
This is not as trivial as it seems. This is a continuation of this issue .
Say I have a Windows Forms user control with the property:
// using System.ComponentModel; [DefaultValue(null)] public object DataSource { … } If I transfer this to VB.NET, I would try this:
'Imports System.ComponentModel <DefaultValue(Nothing)> Public Property DataSource As Object … End Property This will not work, because the compiler has problems with choosing the correct overload of the DefaultValueAttribute constructor :
An overload error is not possible because the available
Newnot the most specific for these arguments:
Public Sub New(value As Boolean): Not the most specific.Public Sub New(value As Byte): Not the most specific.Public Sub New(value As Char): not the most specific.
I am pretty sure that this is because Nothing in VB.NET not only means "null reference" ( null in C #), but also the "default value for" of the parameter type ( default(T) in C #). Because of this ambiguity, every constructor overload is a potential coincidence.
<DefaultValue(CObj(Nothing))> also not work because it is not a constant value.
How exactly do I write this in VB.NET?
PS: <DefaultValue(GetType(Object), Nothing)> is an option, but it bypasses the problem. I'm really wondering if there is a way to use the same constructor for DefaultValueAttribute as the C # version.
"[...] will not work, because the compiler has problems choosing the right overload of the
DefaultValueAttributeconstructor [.]"
The compiler can be provided with the Nothing type-type for the desired type:
<DefaultValue(DirectCast(Nothing, Object))> "
<DefaultValue(CObj(Nothing))>also not work because it is not a constant value.
Fortunately, unlike CObj(Nothing) , the compiler considers DirectCast(Nothing, Object) - and, suprisingly, CType(Nothing, Object) , is also a constant value, so it is accepted.