Search code examples
c#.netreflectionblazor.net-8.0

Accessing public property using reflection using GetProperty c#


I am currently working on a Blazor project in .NET8 and are having some issues trying to access a public property at runtime using reflection.

Issue: I have an array of objects[] at runtime which I cant access the properties value i need once I have drilled down the array to the type using reflection.

I have tried this so far which I am able to see the properties and the types values but cant access them.

            //Have to use reflection as we don't now the type at compile time
            var type = obj[i].GetType();

            //I can see all of the public properties in this array 
            object[] PropertyInfo = type.GetProperties();

            //but when I try and access one of the properties, I get null
            var property = type.GetProperty("Name");

            //The name should be accessable here??
            var name = property.GetValue(obj[i]);

Public Model:

public class MyClass
{
    public int Address { get; set; }
    public string Name { get; set; }

}`

Any help or guidance would be very welcomed as I thought it was due to the property not being public but it actually is.

Thanks in advance for any pointers on this one


Solution

  • My guess is your problem is i. You aren't showing the loop or how your using it.

    Here's a Blazor demo page based on your code that works. Note I use @foreach that defines a local copy of obj in the lowered code.

    @page "/"
    
    <PageTitle>Home</PageTitle>
    
    <h1>Hello, world!</h1>
    
    Welcome to your new app.
    
    @foreach(var obj in _list)
    {
        var type = obj.GetType();
        var property = type.GetProperty("Name");
        var value = property?.GetValue(obj);
            <div>Type: @type.Name - Value: @value  </div>
    }
    
    @code {
        private object[] _list = { 
            new MyClass() { Name="Fred",  Address = 1 }, 
            new MyClass1() { Name="Joe",  Address = 2 },
        };
    
        public class MyClass
        {
            public int Address { get; set; }
            public string? Name { get; set; }
        }
    
        public class MyClass1
        {
            public int Address { get; set; }
            public string? Name { get; set; }
        }
    }
    

    enter image description here