AxD
AxD

Reputation: 3182

How to initialize properties using Reflection?

Given the following sample POCO class:

public class TestClass
{
  public int Id { get; init; }

  public TestClass() {}
}

How can I initialize the Id property using Reflection?

The result should reflect the following static instantiation:

TestClass _ = new TestClass() { Id = 1};

Upvotes: 0

Views: 51

Answers (2)

Michał Turczyn
Michał Turczyn

Reputation: 37460

I can add only alternative version for creating object and setting its property, using Activator.CreateInstance and Type.InvokeMember:

static T CreateAndSetProperty<T>(string propertyName, object propertyValue)
{
    var t = Activator.CreateInstance<T>();
    typeof(T).InvokeMember(propertyName, BindingFlags.SetProperty, Type.DefaultBinder, t, [propertyValue]);
    return t;
}

Upvotes: 2

StriplingWarrior
StriplingWarrior

Reputation: 156634

It's the same as constructing an instance of the class and setting a property. init is a compile-time aid: it doesn't actually change how the class works at run-time.

var type = typeof(TestClass);
var instance = type.GetConstructor(BindingFlags.Public | BindingFlags.Instance, new Type[] { })
    .Invoke(new object[] {});
type.GetProperty("Id").SetValue(instance, 1);

Upvotes: 5

Related Questions