user380432
user380432

Reputation: 4779

C# question on what this code means

I am learning c# code from one of the applications that I run SQL queries from.

I am wondering what the following code does in layman's terms:

  return typeof(ViewModelBase<T>).GetProperty(propertyName) != null;

This is in a function that returns a boolean and a string is passed into it.

ViewModelBase<T> is an abstract class. Can someone also explain what the <T> does in this? I have ideas on these but I'm not sure what exactly is true.

Thanks!

Upvotes: 1

Views: 168

Answers (4)

Fredrik M&#246;rk
Fredrik M&#246;rk

Reputation: 158319

The code piece that you have there is part of a generic type, having a type argument T. Now, we don't see the full method, but I can imagine it looks something like so:

public static bool T HasProperty<T>(string propertyName)
{
    return typeof(ViewModelBase<T>).GetProperty(propertyName) != null;
}

Let's say you have a class Customer:

class Customer
{
    // implementation of class Customer goes here
}

Then you could call the HasProperty method like this:

bool itsThere = HasProperty<Customer>("SomePropertyName");

This means that the HasProperty method will return true if ViewModelBase<Customer> has a property called SomePropertyName, otherwise false.

Upvotes: 1

womp
womp

Reputation: 116977

The code returns true if the type has the property, and false if it doesn't.

This code will be written inside of a generic class, with a type parameter of T. In generics, each time a "hard" type is used with the generic class, the compiler creates a brand new concrete type. So for example, if there was code in your project that was using ViewModelBase<int>, ViewModelBase<string>, and ViewModelBase<MyType>, there would be three concrete types created in the final assembly by the compiler.

Each of these three hypothetical types would have properties and methods. The code shown above would (for all intents and purposes) be duplicated three times, with the type parameter "T" substituted with int, string and MyType in each of the three cases.

GetProperty() would then check to see if the concrete types had the property given in the "propertyName" variable, and return true or false accordingly.

Upvotes: 4

Aliostad
Aliostad

Reputation: 81660

This checks whether ViewModelBase<T> has a property with a name equal to propertyName.

Upvotes: 0

BoltClock
BoltClock

Reputation: 723739

That tells you whether or not the class type ViewModelBase<T>, based on the given type of T, has a public property with the same name as the value of propertyName.

Type.GetProperty() returns a PropertyInfo object if there's such a property; null otherwise. Hence the boolean comparison against null.

Upvotes: 3

Related Questions