Is it possible to assign a value to a field or property before the constructor of the class and using reflection?
Thank you
Yes, there is a sneaky way to do this. The secret sauce is FormatterServices.GetUninitializedObject which will allocate an instance but not run the constructor. You can set fields and properties via reflection and then run the constructor.
A quick example:
class Program
{
static void Main(string[] args)
{
object obj = FormatterServices.GetUninitializedObject(typeof(A));
obj.GetType().GetProperty("I").SetValue(obj, 1);
obj.GetType().GetConstructor(Type.EmptyTypes).Invoke(obj, null);
Console.WriteLine("Done");
}
}
class A
{
public A()
{
if (I != 0)
{
Console.WriteLine("Who set me? I = {0}", I);
}
}
public int I { get; set; }
}
If you are referring to a field or property that is non-static, the answer is no.
You don't actually have an instance of the class before the constructor is called, so you wouldn't have any instance to set the field or property on.
However, if you just want to supply a default value for a class. You can do that by just adding your default assignment after the field or property declaration.
Like so;
public class MyClass
{
public string MyString { get; set; } = "Default Value";
public MyClass()
{
}
}
Now, every instance of MyClass will have a property MyString with a value of "Default Value" until it has been reassigned.
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