Search code examples
c#.netcreateinstance

c# Activator.CreateInstance does not initialize vars


Having Remember.cs:

namespace Tasks
{
    public class Remember : Task
    {
        new public string name = typeof(Remember).Name;
        new public Task.Priority priority = Task.Priority.High;
    }
}

Task.cs:

public abstract class Task
{
    public string name;
    public Task.Priority priority = Task.Priority.Low;

    public enum Priority
    {
        High = 3,
        Medium = 2,
        Low = 1,
    }
}

When i create an instance of this class by using:

Task task = (Task)Activator.CreateInstance(typeof(Remember));
Debug.Log(task.name + " - " + task.priority);

Task's name is null and priority is the lowest number available in Task.Priority enum rather than the selected one (High).

Why does Activator.CreateInstance not initialize those vars?


Solution

  • You are re-declaring the variables in your subclass (via the new keyword), which gives you a separate set of variables than your Task class. Instead, you should set the Task variables directly from the constructor of the Remember class.

    namespace Tasks
    {
        public class Remember : Task
        {
            public Remember()
            {
                name = typeof(Remember).Name;
                priority = Task.Priority.High;
            }
        }
    }
    

    As others have pointed out, this has nothing to do with Activator.CreateInstance. You get the same behavior when you use new Remember().