Django
Django

Reputation: 381

How can I force a child class to assign a unique value to an inherited field?

Say I have a parent class:

Public MustInherit Class ParentClass
    Protected str As String
    Public MustOverride Sub Method()
End Class

And then I have a child class:

Public Class ChildClass
    Inherits ParentClass
    Public Overrides Sub Method()
    End Sub
End Class

At the moment I have no way to ensure that str is assigned a unique value (a value which will be different for each class that inherits ParentClass).

Is there any way to force any child classes (even ones that I don't create) to assign str a value, similar to how MustOverride forces the child class to implement Method()? I thought there might a MustAssign keyword but there isn't.

Upvotes: 1

Views: 181

Answers (3)

Pablo Fébolo
Pablo Fébolo

Reputation: 116

Use name Class, ensure the unique value

Public MustInherit Class ParentClass
    Protected str As String = Me.GetType.Name
    Public MustOverride Sub Method()
End Class

Beware, in your solution, there is nothing to prevent two daughters classes with the same initialization.

Upvotes: 1

Django
Django

Reputation: 381

Aha! I think I've reasoned out a way to do this myself.

I will create a protected constructor in ParentClass that takes a String and assign it to the field.

In ParentClass:

Protected Sub New(ByVal s As String)
    Me.str = s
End Sub

Now, every class must implement a constructor that calls the single ParentClass constructor which takes a String.

In ChildClass

Public Sub New()
    MyBase.New("String")
End Sub

This seems to solve my problem.

Is there a better method to solving this problem, or have I hit the nail on the head?

Upvotes: 1

yu_sha
yu_sha

Reputation: 4400

One of the possible patterns is to use a getter function instead of a field. Define it in each of the child classes. It may or may not be what you want.

Public MustOverride Function Str() As String

Upvotes: 0

Related Questions