Question

Ok, so I'm a C# coder, and I have trouble even reading VB.NET, so please forgive what may turn out to be an incredibly dumb question. But I have some code which looks like this:

Function GetName(sourceObject as Object) as String
    return sourceObject.Name
End Function

So, ignoring the fact that the syntax is probably wrong - how does VB.NET get the Name property from sourceObject? Inspecting it at run-time reveals that sourceObject is of a type that supports a property called Name with a getter, but what does VB.NET do in this case? Is there some extra code that is being generated by the compiler to somehow cast this automagically at run-time?

As you may be able to tell, I'm a little confused. Thanks in advance!

Was it helpful?

Solution

This is a case of late binding. So, if the sourceObject contains a property as Name it will return the value otherwise it will just throw an error that property not found.

Late binding in C# requires reflection so it throws compile time error, whereas in vb.net it can be done without reflection.

The Visual Basic compiler performs a process called binding when an object is assigned to an object variable. An object is early bound when it is assigned to a variable declared to be of a specific object type. Early bound objects allow the compiler to allocate memory and perform other optimizations before an application executes. By contrast, an object is late bound when it is assigned to a variable declared to be of type Object. Objects of this type can hold references to any object.

OTHER TIPS

If you are using c# 4.0 then you can try this.

return ((dynamic)SourceObject).Name;

Because of inherent late binding, all VB variables of type Object are equivalent to c# objects which have been cast to dynamic -- or to put it another way, c# added dynamic in order to gain functional parity with VB.

So, the equivalent c# code would be ((dynamic) sourceObject).Name

I would look into doing this with Generics or an interface if possible, as thats a cleaner design.

Just be aware that VB's Late Binding bypasses type checking with your compiler. If the Object being passed in doesn't have a Name property, an exception could be raised at run time.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top