Andy5
Andy5

Reputation: 2405

VB.Net and access via a variable of an interface type

How do I make the properties of a class available in an inheriting class, for a variable that is declared to be the type of one of the interfaces implemented by that class?

What I have done so far is to create an abstract class MyAbstract with the keyword MustInherit and in the inheriting class MyInheritingClass I have added inherits and then the name of the abstract class. Now this is all fine, but in my inheriting class, if I create an interface on that class MyInterface and use that interface elsewhere in my code, I have then found that I cannot see the properties from my abstract class, on the variable declared with that interface.

Am I doing something wrong here, or is there something else that I need to do?

An example would be as follows:

Public MustInherit Class MyAbstract
    Private _myString as String
    Public Property CommonString as String
        Get
            Return _myString
        End Get
        Set (value as String)
            _myString = value
        End Set
    End Property
End Class

Public Class MyInheritingClass
    Inherits MyAbstract
    Implements MyInterface

    Sub MySub(myParameter As MyInterface)
        myParameter.CommonString = "abc" ' compiler error - CommonString is not a member of MyInterface.
    End Sub

    'Other properties and methods go here!'
End Class

So, this is what I am doing, but when I use MyInterface, I cannot see the properties of my Abstract Class!

Upvotes: 0

Views: 12632

Answers (1)

Steven Doggart
Steven Doggart

Reputation: 43743

Unless I've completely misunderstood your question, I'm not sure why you are confused by this behavior. Not only is that how it should work, but that is also how it works in c#. For instance:

class Program
{
    private abstract class MyAbstract
    {
        private string _myString;
        public string CommonString
        {
            get { return _myString; }
            set { _myString = value; }
        }
    }

    private interface MyInterface
    {
        string UncommonString { get; set; }
    }

    private class MyInheritedClass : MyAbstract, MyInterface
    {
        private string _uncommonString;
        public string UncommonString
        {
            get { return _uncommonString; }
            set { _uncommonString = value; }
        }
    }

    static void Main(string[] args)
    {
        MyInterface test = new MyInheritedClass();
        string compile = test.UncommonString;
        string doesntCompile = test.CommonString;  // This line fails to compile
    }
}

When you access an object through any interface or base class, you will only ever have access to the members that are exposed by that interface or base class. If you need to access a member of MyAbstract, you need to cast the object as either MyAbstract or MyInheritedClass. This is true in both languages.

Upvotes: 7

Related Questions