0

I have declared a "variable" of type OBJECT. I have also declared a class named TEST which has a property "name". My understanding is that in the statement variable = New test() the compiler is creating a new instance of the class TEST and storing the reference/memory address of that newly created instance in "variable". The idea is that an object type of variable should be able to store any type of data or its reference. By that logic using the member accessor operator I should be able to access the property "name" using "variable". But I am unable to. Can someone please explain why and how to access the property when the reference to the instance is being stored in an object type variable?

Module Program
    Sub Main()
        Dim variable As Object
        variable = New test()
        Console.WriteLine("Value: {0}   Type: {1}", variable, variable.GetType())
        'Output is Type: Object_Data_Type.test --> Works
        'However we cannot access the property name of the class TEST through "varibale"
        Console.ReadLine()
    End Sub
End Module

Public Class test
    Public Property name As String
End Class
3
  • 1
    along with the provided answer, it's advisable to avoid using the base Object type when possible. Commented Jun 28, 2020 at 22:40
  • 1
    It's not that you're not able to. It's that the compiler won't allow it with Option Strict On. Accessing a member of a type more derived than that of the reference, e.g. a member of type Test on a reference of type Object, requires late binding, i.e. it cannot be confirmed to be valid until run time. There are times where late binding is required but they are very much the exception. Basically, there's no good reason to be trying to do what you're doing in the vast majority of cases so don't do it. Commented Jun 29, 2020 at 1:20
  • You should do some reading on early and late binding. Given that Option Strict Off is the default for VB.NET, all developers should understand what they are and why you should immediately turn Option Strict On and leave it On in all cases except where late binding is legitimately required. Commented Jun 29, 2020 at 1:21

1 Answer 1

1

Because an Object doesn't have a name property, and (on the outside) your variable looks like Object. If you want it to look like Test you'll have to cast it:

Console.WriteLine("Value: {0}   Type: {1}", DirectCast(variable, Test).name, variable.GetType())
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.