Printer Friendly Version      Send     
Click to Rate and Give Feedback
MSDN
MSDN Library
Visual Studio .NET
Component Authoring
 Default Properties for Your Compone...
Visual Basic and Visual C# Concepts
Default Properties for Your Components

You might want to implement a default property for your component. If you mark a property as the default property of your component, the property name can be omitted in both Visual Basic and C# code. That is, the following lines are equivalent.

' Visual Basic
System.Diagnostics.Debug.WriteLine(myWidgets(3).Status)
System.Diagnostics.Debug.WriteLine(myWidgets.Item(3).Status)

You can create default properties that accept parameters (such as the Item property of a collection), but cannot create a default property that does not accept parameters.

Visual Basic Note   In previous versions of Visual Basic, you were allowed to implement parameterless default properties. This is no longer allowed. For details, see Default Property Changes in Visual Basic

The C# equivalent of a default Item property is an indexer. A C# indexer appears to a Visual Basic programmer as a default Item property, and a Visual Basic default property appears to a C# programmer as an indexer. The following line shows the usage of the indexer for the myWidgets object.

// C#
System.Diagnostics.Debug.WriteLine(myWidgets[1].Status);

Enabling this shortcut makes sense only if the primary purpose of a component is to contain other objects. Examples of a default property (Visual Basic) and an indexer (C#) are shown below.

' Visual Basic
' A class that contains many Widgets
Public Class Widgets
   'Default property implementation
   Default Public Property Widget(ByVal I As Integer) As Widget
      Get
      ' Implementation code to return a widget goes here.
      End Get
      Set(ByVal Value As Widget)
      ' Implementation code to set a widget goes here.
      End Set
   End Property
End Class

// C#
// Class that contains many Widgets.
public class Widgets
{
   // Indexer implementation.
   public Widget this[int index]
   {
      get
      {
         // Insert code to return a Widget.
      }
      set
      {
         // Insert code to set a Widget.
      }
   }
}
// Insert client code.

See Also

Default Property Changes in Visual Basic | Implementing Properties, Methods, Members, and Events in Components

© 2008 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Page view tracker