Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 682
mrbradleyt Avatar asked Nov 10 '08 22:11

mrbradleyt


People also ask

How to use GetProperty in c#?

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.

How do I get a property type from PropertyInfo?

Use PropertyInfo. PropertyType to get the type of the property. Show activity on this post.

Why would you use reflection C#?

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.


2 Answers

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.)

like image 149
Jon Skeet Avatar answered Nov 15 '22 09:11

Jon Skeet


Try adding the scope BindingFlags like so:

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

This works for me.

like image 45
Jeffrey Harrington Avatar answered Nov 15 '22 09:11

Jeffrey Harrington