Alex Rivera | Logout

Is there a way to Overload a Property in .NET

Asked 2010-02-10T15:37:03.857
14

I've done plenty of Method Overloading, but now I have an instance where I would like to Overload a Property. The IDE in Visual Studio seems to allow it, since I can actually set up the two overloads, but I get an error saying it is not valid because they only differ in type. I think I'm missing something in my syntax?

I want to be able to use two (or more) different custom classes as the Type for my property.

Public Overloads Property myFlexibleProperty() As myCustomClass1
      Get
         Return _myFlexibleProperty1
      End Get
      Set(ByVal value As myCustomClass1)
         _myFlexibleProperty1 = value
      End Set
   End Property

   Public Overloads Property myFlexibleProperty() As myCustomClass2
      Get
         Return _myFlexibleProperty2
      End Get
      Set(ByVal value As myCustomClass2)
         _myFlexibleProperty2 = value
      End Set
   End Property

All of the help I have found so far has been concerning Overloading Methods. Despite what the IDE is letting me do, I'm beginning to think this is not possible?

Edit
Report

2 Answers

17

To overload something--method or property--you need for it to accept a different set of parameters. Since properties in VB.NET can accept parameters, I guess you can overload them; but they have to be different.

So you could do this:

Public Overloads Readonly Property Average() As Double
Public Overloads Readonly Property Average(ByVal startIndex As Integer) As Double

But not this:

Public Overloads Readonly Property Average() As Double
Public Overloads Readonly Property Average() As Decimal
answered 2010-02-10T15:39:14.757
1

have you tried using a class based on an interface? Then, you could have different classes based on the same common interface and the property associated to the interface type, not the specific class itself.

answered 2010-02-10T15:42:18.020

Your Answer