Sougata
Sougata

Reputation: 337

How to access properties of a class using Object type variable?

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

Upvotes: 0

Views: 576

Answers (1)

Caius Jard
Caius Jard

Reputation: 74730

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())

Upvotes: 1

Related Questions