Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a property exists in a class

I try to know if a property exist in a class, I tried this :

public static bool HasProperty(this object obj, string propertyName) {     return obj.GetType().GetProperty(propertyName) != null; } 

I don't understand why the first test method does not pass ?

[TestMethod] public void Test_HasProperty_True() {     var res = typeof(MyClass).HasProperty("Label");     Assert.IsTrue(res); }  [TestMethod] public void Test_HasProperty_False() {     var res = typeof(MyClass).HasProperty("Lab");     Assert.IsFalse(res); } 
like image 331
Kris-I Avatar asked Mar 11 '13 14:03

Kris-I


People also ask

How do you check if a property exists in a Model C#?

if(typeof(ModelName). GetProperty("Name of Property") != null) { //whatevver you were wanting to do. }

How do you check if a property exists in an object TypeScript?

To check if a property exists in an object in TypeScript: Mark the specific property as optional in the object's type. Use a type guard to check if the property exists in the object. If accessing the property in the object does not return a value of undefined , it exists in the object.


1 Answers

Your method looks like this:

public static bool HasProperty(this object obj, string propertyName) {     return obj.GetType().GetProperty(propertyName) != null; } 

This adds an extension onto object - the base class of everything. When you call this extension you're passing it a Type:

var res = typeof(MyClass).HasProperty("Label"); 

Your method expects an instance of a class, not a Type. Otherwise you're essentially doing

typeof(MyClass) - this gives an instanceof `System.Type`.  

Then

type.GetType() - this gives `System.Type` Getproperty('xxx') - whatever you provide as xxx is unlikely to be on `System.Type` 

As @PeterRitchie correctly points out, at this point your code is looking for property Label on System.Type. That property does not exist.

The solution is either

a) Provide an instance of MyClass to the extension:

var myInstance = new MyClass() myInstance.HasProperty("Label") 

b) Put the extension on System.Type

public static bool HasProperty(this Type obj, string propertyName) {     return obj.GetProperty(propertyName) != null; } 

and

typeof(MyClass).HasProperty("Label"); 
like image 74
Jamiec Avatar answered Sep 28 '22 11:09

Jamiec