Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to Overload a Property in .NET

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?

like image 391
GSTD Avatar asked Feb 10 '10 15:02

GSTD


People also ask

Can we overload properties in C#?

You cannot overload a property: A property cannot be overloaded. It means that one can only put a single get and set accessor and mutator in a class respectively.

Can we overload a Web method?

Yes. The WebMethod attribute takes a MessageName parameter that allows you to "overload" the method.

What is overloading asp net?

Overloading is the creation of more than one procedure, instance constructor, or property in a class with the same name but different argument types.


2 Answers

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
like image 189
Dan Tao Avatar answered Oct 24 '22 12:10

Dan Tao


This should not be possible. You are effectively trying to make a property that could return two different types. There is no way for the system to make the determination as to what you are trying to call.

You will have to give unique property names to each.

like image 36
Mitchel Sellers Avatar answered Oct 24 '22 12:10

Mitchel Sellers