Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set field or property value before constructor

Tags:

c#

reflection

Is it possible to assign a value to a field or property before the constructor of the class and using reflection?

Thank you

like image 486
Junior Avatar asked Nov 20 '16 03:11

Junior


2 Answers

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; }
}
like image 168
Mike Zboray Avatar answered Sep 22 '22 02:09

Mike Zboray


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.

like image 34
Matt Hensley Avatar answered Sep 21 '22 02:09

Matt Hensley