VRM VRM - 2 months ago 21
C# Question

Are constructors by default public?

I was asked this question in my examination

class main
{
static long afield = 123;

static main()
{
Console.WriteLine(afield);
}

main()
{
afield = 1000;
Console.WriteLine(afield);
}
}

static void Main(String[] args)
{
main obj = new main();
}


What is the output


  • a) 1000123

  • b) 123

  • c) No output

  • d) 1231000



I check a) and it was wrong.

When I ran the program, I got an error stating that ConsoleApplication1.main.main() is inaccessible due to its protection level.

Aren't constructors supposed to be public by default? Why was I getting this error?

Answer

Omitting the access modifier (public, private, internal or protected) on any member (constructor, field, property, method, event, etc.) will leave the member private by default.

However if you don't define any constructors yourself, the class will implicitly get a parameterless public constructor. If this weren't so, you would have to write an empty public constructor for every class you create.