So I had this Singleton code
public class Foo
{
private static Foo instance;
private Foo() { }
public static Foo Instance
{
get
{
if (instance == null) instance = Activator.CreateInstance<Foo>();
return instance;
}
}
}
Which didn't work because Foo's constructor is set to private (throws an exception that no parameterless constructor for that class is found).
Traditional new Foo() works there though (of course). I'm aware that Activator cannot access Foo's private constructor due to access restrictions, but I thought that every object instantiation was done by Activator: so why doesn't Activator work in that context?
Thanks!
Activator is expecting only public constructors. If you're interested in something other than public, then you need to call it differently:
(Foo)Activator.CreateInstance(typeof(Foo), nonPublic:true);
Unfortunately, the generic version doesn't really provide any additional options... Which means you get some unboxing. However, you're also doing reflection, which is already slow... So I would guess this is more academic and less performance concerned.
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