How to use .Net reflection to search for a property by name, ignoring case?

I had the following code snippet that is looking for an instance property by name:

var prop = Backend.GetType().GetProperty(fieldName); 

Now I want to ignore the fieldName case, so I tried the following:

 var prop = Backend.GetType().GetProperty(fieldName, BindingFlags.IgnoreCase); 

... no dice. Now prop will not find field names that have an exact case.

Therefore ..... How to use .Net reflection to search for a property by name, ignoring the case?

+5
reflection c #
Nov 10 '08 at 22:15
source share
2 answers

You need to also specify BindingFlags.Public | BindingFlags.Instance BindingFlags.Public | BindingFlags.Instance :

 using System; using System.Reflection; public class Test { private int foo; public int Foo { get { return foo; } } static void Main() { var prop = typeof(Test).GetProperty("foo", BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase); Console.WriteLine(prop); } } 

(If you do not specify any flags, public, instance and static are provided by default. If you specify this explicitly, I suggest you specify only one instance or static if you know what you need.)

+13
Nov 10 '08 at 22:25
source share

Try adding the BindingFlags scope as follows:

 var prop = Backend.GetType().GetProperty(fieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase); 

This works for me.

+2
Nov 10 '08 at
source share



All Articles