I want to create some instances of classes via Activator.CreateInstance(...)
. All classes inherit same abstract class. The constructor has one parameter.
Classes and constructors should not be public.
This is what I want in code (but not get):
internal abstract class FooAbstract
{
protected Bar MyProperty { get; set; }
// Constructor is only need in concreat classes of FooAbstract
protected FooAbstract(Bar barProperty)
{
MyProperty = barProperty;
}
}
internal class Foo : FooAbstract
{
// Internal is enough, public is not necessary
internal Foo(Bar barProperty)
: base(barProperty)
{
}
// Many more Foo´s ...
internal class Creator()
{
private object CreateAFoo<T>() where T : FooAbstract
{
T someFoo = (T)Activator.CreateInstance(typeof(T), barProperty);
}
}
But this throws an Exception Constructor on type 'Foo' not found
.
When I change constructor of FooAbstract
and Foo
to public
all will be fine (classes stay internal
!).
So I can understood that Activator.CreateInstance(...)
needs public access (he comes from outside the package), but why is this possible with remaining internal classes?
Until now I thought that when class is internal and constructor is public it would be the same as class is internal and constructor is also internal (to kind of hierarchic access layers) ... but this seems to be wrong!
Can somebody help me to understand what happened here - why public constructors in internal classes do work?