Let's consider the following first example:
public class ClassNameExample
{
private ClassNameExample()
{
//code goes here
}
}
Now, if I try to instantiate the ClassNameExample
class from within the same assembly, I'll get an "Inaccessible due to it's protection level" compiler error message (CS0122).
However, if I try to instantiate the ClassNameExample
class from a different assembly, I'm getting a "The type 'class' has no constructors defined" compiler error message (CS0143)
Can someone explain why the compiler sees them different?
For reference, I've tried this in Visual Studio 2012, .NET 4.5.
I tried to see what Microsoft.CSharp.CSharpCodeGenerator does and to figure out where the errors are populated, but the code at the end relies on external files.
The only answer I can give you is: if you create an instance with
Assembly.GetExecutingAssembly().CreateInstance("ClassNameExample");
or even with Activator.CreateInstance("Your assembly", "ClassNameExample");
both return null because they rely on public constructor, check the flags
public object CreateInstance(string typeName)
{
return this.CreateInstance(typeName, false, BindingFlags.Instance | BindingFlags.Public, (Binder) null, (object[]) null, (CultureInfo) null, (object[]) null);
}
Activator.CreateInstance(assemblyName, typeName, false, BindingFlags.Instance | BindingFlags.Public | BindingFlags.CreateInstance, (Binder) null, (object[]) null, (CultureInfo) null, (object[]) null, (Evidence) null, ref stackMark);
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