views:

395

answers:

3

What should be more proper or what is recommended to use in VB.NET from either reflection vs. late binding:

'Type can be various objects that have a common property for sure.'
Dim type = sender.GetType()
Dim prop = type.GetProperty("Text", 20)
Dim value = property.GetValue(sender, Nothing)

versus:

Dim value = sender.Text
A: 

Under the covers they are both doing the same thing (relatively speaking). VB.NET's late-binding feature is done via assembly metadata queries at runtime which is exactly what reflection is all about.

One of the benefits to your first approach is that you have an opportunity to handle errors in a more finely-grained manner.

Andrew Hare
I guess I will choose what's more readable and convinient - better said, I will take advantage on VBs features!
Shimmy
A: 

Isn't sender.Text always a string though? So the type of value can be inferred at compile time, making the latter an example of early binding?

Paul Creasey
no, it always returns 'object', so both are the same.
Shimmy
A: 

If you do use late binding, you can put the method that extracts the properties into a partial class with Option Explicit = Off. That way, you still have type checking in the rest of your code.

Jules
I never turn Option Explicit, that's one of the reasons I love VB so much
Shimmy