Joshua Frank
Joshua Frank

Reputation: 13838

Why does this repeated member not cause a compiler error?

Here's the code:

Public Class GridModel
    Public DataSource As IDataSource
End Class

Public Class GridModel(Of TDataItem)
    Inherits GridModel

    Public DataSource As IDataSource(Of TDataItem)
End Class

I would have thought that this wouldn't compile, because the two members have the same name and differ only by return type, but the VB compiler allows it. Why doesn't the compiler prevent this?

Upvotes: 0

Views: 34

Answers (2)

jmcilhinney
jmcilhinney

Reputation: 54417

When I copy your code into the IDE I get the following warning:

variable 'DataSource' conflicts with variable 'DataSource' in the base class 'GridModel' and should be declared 'Shadows'.

That is your explanation, i.e. the member in the derived class is shadowing the member in the base class.

Upvotes: 0

Ian CT
Ian CT

Reputation: 1411

Why doesn't the compiler prevent this?

Here is an answer from Programmers' StackExchange.

According to MSDN,

If the derived class variable shadows a variable in the base class, it hides the base class version.

And,

However, you can access the base class variable by qualifying it with the MyBase keyword.

Usually, there are warnings issued once this happens.

Upvotes: 2

Related Questions