Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this a bug? Activator.CreateInstance with private access modifier constructor?

Tags:

c#

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!

like image 971
Gaspa79 Avatar asked Dec 27 '25 15:12

Gaspa79


1 Answers

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.

like image 118
poy Avatar answered Dec 30 '25 04:12

poy