Origin
Origin

Reputation: 2023

Getting PropertyInfo without an instance of the class

I have started using reflection and am a bit confused about getting PropertyInfo.

I do something like this and it works:

Dim x as New MyClass
Dim prop as PropertyInfo = x.GetType.GetProperty("Name")

I don't understand why I must have an instance of the class in order to get a property from it. If GetType returns a Type object, why couldn't I just reference the type itself?

Dim prop as PropertyInfo = GetType(MyClass).GetProperty("Name")

or

Dim prop as PropertyInfo = MyClass.GetType.GetProperty("Name")

Upvotes: 0

Views: 704

Answers (2)

user117499
user117499

Reputation:

A safer way:

Dim prop as PropertyInfo = GetType(MyClass).GetProperty(NameOf(MyClass.MyProperty))

Upvotes: 0

SLaks
SLaks

Reputation: 887453

Dim prop as PropertyInfo = GetType(MyClass).GetProperty("Name")

That is exactly correct.

Upvotes: 1

Related Questions