Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# compiler error differences between CS0122 and CS0143

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.

like image 804
Cosmin Avatar asked Nov 08 '22 23:11

Cosmin


1 Answers

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);
like image 162
Zinov Avatar answered Nov 14 '22 23:11

Zinov