views:

122

answers:

4

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!

+4  A: 

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.

womp
Type of what? That what I dont really understand
Sorry, was writing out a more detailed answer. Hope my edit clarifies it for you a bit.
womp
+3  A: 

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.

BoltClock
A: 

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

Aliostad
+1  A: 

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.

Fredrik Mörk