Implicitly and Explicitly calling default constructor of a class in C# 3.0

Hi, I have 2 questions about C# 3.0.......

What is the difference between
"implicitly calling the default constructor"
"explicitly calling the default constructor"
of a class?

Any advantages or reason to use a particular one?
(see attached code snippet)

class Program
        static void Main(string[] args)
            // example 1, old school
            MyClass mclass1 = new MyClass();

            //example 2, new with C# 3.0, implicitly calls the classes default constructor.
            MyClass mclass2 = new MyClass { mystring = "test2" };

            //example 2, new with C# 3.0, explicitly calls the classes default constructor.
            MyClass mclass3 = new MyClass () { mystring = "test3" };


    class MyClass 
        public string mystring { get; set; }

Open in new window

silentthread2kSenior Software EngineerAsked:
Who is Participating?
Richard LeeConnect With a Mentor Software EnthusiastCommented:
Example 2 & 3 are the same. There is no difference between the statements. There is no advantage or change in how things work by explicitly or implicitly calling the default constructor.

silentthread2kSenior Software EngineerAuthor Commented:
Thanks, I will award you points, but I need more clarification...

What do does "implicitly" and "explicitly" mean in the context it is being used.
Miguel OzConnect With a Mentor Software EngineerCommented:
This is the new syntax called "object initializer syntax"
Both approaches produce the same result, the difference is that "explicit constructor" clearly specifies you are using the defalut constructor
Miguel OzConnect With a Mentor Software EngineerCommented:
Implict means you are using the "()" to specify you are using the default constructor. "Explicit" you are specifying the default constructor
Richard LeeConnect With a Mentor Software EnthusiastCommented:
The option of specifying the constructor is provided with the new syntax in c# 3.0. If no constructor is specified then the default is chosen however you can also choose to use non-default constructors before the initialization of the properties.

var first = new MyClass { mystring = "test2" };
var second = new MyClass() { mystring = "test2" };

first & second are the same.

Now suppose there was a non-default constructor that accepts a string and sets mystring to that value.

var third = new MyClass("test3") { mystring = "test2" };

the value should be = test2

Of course no one would do this, but its useful in other cases. Dependency Injection, IoC, etc.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.