Differences in C # Compiler Errors between CS0122 and CS0143

Consider the following first example:

public class ClassNameExample { private ClassNameExample() { //code goes here } } 

Now, if I try to create an instance of the ClassNameExample class from the same assembly, I get the error "Invalid because of its security level" ( CS0122 ).

However, if I try to create an instance of the ClassNameExample class from another assembly, I get the class โ€œTypeโ€ that has no constructors defined with โ€œcompiler error message ( CS0143 )

Can someone explain why the compiler sees them different?

For reference, I tried this in Visual Studio 2012, .NET 4.5.

+5
source share
1 answer

I tried to understand what Microsoft.CSharp.CSharpCodeGenerator does, and figure out where the errors are populated, but the code at the end depends 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 a public constructor, check 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); 
+1
source

Source: https://habr.com/ru/post/1238135/


All Articles