CSharp - What is the output, Constructor and field


What is the output from the following code

using System;
class MyClass
    int i;
    public MyClass(int i)
        this.i = i;
class Program
    static void Main(string[] args)
        MyClass ob2 = new MyClass();

Click to view the answer

Compilation error:  'MyClass' does not contain a constructor that takes 0 arguments.


In C#, we can get a default 0 argument constructor if we do not define any constructor.

If we have a parameterized constructor, the compiler will not add a default 0 argument constructor for us.

if you want to remove this compilation error, you have following choices:

You can define one more custom constructor like this:

public MyClass() { } 

You can remove the custom constructor declaration from this program.

You can supply the necessary integer argument inside your Main() method like this:

MyClass ob2 = new MyClass(25); 

Related Quiz