I had the following line snippet of code that searches for a propery of an instance by name:
var prop = Backend.GetType().GetProperty(fieldName);
Now I want to ignore the case of fieldName, so I tried the following:
var prop = Backend.GetType().GetProperty(fieldName, BindingFlags.IgnoreCase);
... No dice. Now prop won't find field names that have the exact case.
Hence..... How do I use .Net reflection to search for a property by name ignoring case?
GetProperties() Method Syntax: public System. Reflection. PropertyInfo[] GetProperties (); Return Value: This method returns an array of PropertyInfo objects representing all public properties of the current Type or an empty array of type PropertyInfo if the current Type does not have public properties.
Use PropertyInfo. PropertyType to get the type of the property. Show activity on this post.
Reflection in C# is used to retrieve metadata on types at runtime. In other words, you can use reflection to inspect metadata of the types in your program dynamically -- you can retrieve information on the loaded assemblies and the types defined in them.
You need to specify BindingFlags.Public | BindingFlags.Instance
as well:
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);
}
}
(When you don't specify any flags, public, instance and static are provided by default. If you're specifying it explicitly I suggest you only specify one of instance or static, if you know what you need.)
Try adding the scope BindingFlags like so:
var prop = Backend.GetType().GetProperty(fieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase);
This works for me.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With