Default properties in VB.NET?

Well, the .NET framework does have a notion of a default member. Key ingredients are the DefaultMemberAttribute class and Type.GetDefaultMembers(). In VB.NET, specifying the default member is part of the language syntax:

  Public Class Sample
    Private mValue As Integer
    Default Public ReadOnly Property Test(ByVal index As Integer) As Integer
      Get
        Return index
      End Get
    End Property
  End Class

Use it like this:

  Sub Main()
    Dim s As New Sample
    Console.WriteLine(s(42))
    Console.ReadLine()
  End Sub

The compiler implements this by emitting [DefaultMember] automatically. This however has a restriction, the property must have an index argument, specifically to avoid the syntax ambiguity. This restriction is not enforced when specifying the attribute explicitly:

  <System.Reflection.DefaultMember("AnotherTest")> _
  Public Class Sample
    Public ReadOnly Property AnotherTest() As Integer
      Get
        Return 42
      End Get
    End Property
  End Class

But that default member would only be accessible as a default by a language that allows such syntax. For which I don’t know an example in .NET, this was used back in the COM days, like VB6. Also the core reason behind VB6 having the Set keyword, it solves the ambiguity and states “I mean the object, not the object’s default property”. Very painful syntax detail for many beginning Visual Basic programmers back then.

C# has the exact same rules, but doesn’t allow the same kind of flexibility. You’ve probably seen the indexer before:

  public class Sample {
    public int this[int index] {
      get { return index; }
    }
  }

This code also makes the compiler output the [DefaultMember] attribute. The named property in that attribute is “Item”. And that’s why you see the indexer documented and indexed in the MSDN Library as “Item”.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)