John Bustos
John Bustos

Reputation: 19544

Override a default property value in an inherited class

Suppose I have the following parent class defined:

Public Class Parent

    Public Property Prop1 As String = "MyDB1"

End Class

And I wish to inherit it, but want that property to have a different value for the child class.

I figured I could do it as follows:

Public Class Child
    Inherits Parent

    Public Sub New()
        MyBase.New()
        MyBase.Prop1 = "MyDB2"
    End Sub

End Class

But I was wondering if this was the best way to do this or if there is something like an Overridable property OR if this is just bad programming practice as a whole?

Thanks!

Upvotes: 1

Views: 2184

Answers (2)

sellmeadog
sellmeadog

Reputation: 7517

Based on your comment, here's my opinion:

  • If you are in control of the base class, make it Overridable if the intent is to have it's value change based on business rule(s) of the derived type(s)
  • If you are not in control of the base class, and you need to "override" the property, you can "hide" the base property; in C#, it would look something like new public int MyProperty { ... } but I'm not sure how this is accomplished in VB
  • If all you need is for the property to return a different value, then what you've done seems fine

Upvotes: 2

Behnam Esmaili
Behnam Esmaili

Reputation: 5967

in c# for letting a property to be overridable you can mark class member as virtual and vb.net equvale of this keyword is Overridable.

public virtual int MyProperty {get;set;}

this property can be overrided in sub class like this :

 public override int MyProperty {
  get{ 
         //return some other thing
     }
  } 

Vb.NET equivalent :

in super class :

 Public Overridable Property MyProperty As Integer
        Get

        End Get

        Set

        End Set

    End Property

and in the sub class :

  Public Overrides Property MyProperty As Integer
        Get
                //return some other thing
        End Get

    End Property

Upvotes: 3

Related Questions