0

Can someone please explain to me how the Activator.CreateInstance method is able to create instances of a protected class?

public abstract class File
{
    public string Name {get; set;}
}

public class ExcelFile : File
{
    protected ExcelFile()
    {
    }
}

It's not possible to create a new instance of the object by calling ExcelFile file = new ExcelFile();

'ExcelFile' is inaccessible due to its protection level

Yet it's possible to create it using:

Type type = Type.GetType("ConsoleApplication.ExcelFile");
object o = Activator.CreateInstance(type, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.CreateInstance, null, new object[0], CultureInfo.InvariantCulture);

The above code was lifted from the BCL WebRequest.Create() method and would like to what parameters in Activator.CreateInstance is allowing reflection to create an instance of a protected class?

Note: I plan to use the Activator.CreateInstance in a factory class to return new objects so would like to have a better understanding how it works.

Fixer
  • 5,985
  • 8
  • 40
  • 58

1 Answers1

1

Reflection doesn't care about access modifiers

Daniel
  • 30,896
  • 18
  • 85
  • 139