Alexandru
Alexandru

Reputation: 12902

How can I use reflection to set this object's property?

I have an external library I am using, namely Aspose.Email.dll (available on NuGet). It has a PageInfo class. Go To Definition shows the following for it in Visual Studio:

using System;

namespace Aspose.Email
{
    public class PageInfo
    {
        protected PageInfo next;

        public int AbsoluteOffset { get; }
        public int ItemsPerPage { get; }
        public bool LastPage { get; }
        public virtual PageInfo NextPage { get; }
        public int PageOffset { get; }
        public int TotalCount { get; }
    }
}

Long story short, I need to create a PageInfo object. How can I create one using Reflection and also set its ItemsPerPage property?

I have tried this:

var result = (PageInfo)FormatterServices.GetUninitializedObject(typeof(PageInfo));
typeof(PageInfo).GetProperty("ItemsPerPage", BindingFlags.Instance | BindingFlags.Public).SetValue(result, 1);

The problem is that SetValue errors out with Property set method not found.

Upvotes: 1

Views: 705

Answers (1)

Eli Arbel
Eli Arbel

Reputation: 22739

Getter-only properties do not have setters. They use a readonly backing field that can only be set in the constructor.

You can change the properties to have private setter, e.g.

public int ItemsPerPage { get; private set; }

If you do not have access to the code, you can find the matching field using GetField and set its value.

typeof(PageInfo).GetTypeInfo().DeclaredFields
    .First(f => f.Name.Contains("ItemsPerPage")).SetValue(result, 1);

Upvotes: 2

Related Questions