default constructors confusing?

So on the msdn forums it states that default constructors are parameterless constructors and if you don’t have a constructor the compiler will create a default constructor for you automatically. Does this not apply to parameterized constructors? are the values not set to their defaults?

The thing about this is each value is set to it’s default but if i were to change the fields name or maxHitPoints to something else i expect it to change it to 0 or null but that does not happen.

 class ExampleOne
    {
  
        static void Main()
        {
            ExampleTwo ex1 = new ExampleTwo();
            Console.WriteLine(ex1.number == 0);
            Console.WriteLine(ex1.myString == null);
        }
    }
    class ExampleTwo
    {
        public int number;
        public string myString;
    }

Here i expect it to not set the fields to their defaults.

class ExampleOne
    {

        static void Main()
        {
            ExampleTwo ex1 = new ExampleTwo(10);
            Console.WriteLine(ex1.maxHitPoints == 0);
            Console.WriteLine(ex1.name == null);
        }
    }
    class ExampleTwo
    {
        public int maxHitPoints = 5;
        public string name = "joe";
        public ExampleTwo(int hp)
        {
            Console.WriteLine(hp);
        }

    }

Where did i go wrong?

In the second part the “ExampleTwo” ctor should be
{
maxHitPoints = hp;
}
or is anything wrong?

class ExampleTwo
    {
        public int maxHitPoints = 5;
        public string name = "joe";
        public ExampleTwo(int hp)
        {
            Console.WriteLine(hp);
        }
    }

A constructor is just a regular piece of code - there is nothing particularly magical about it. Why would maxHitPoints and name be different in this case? You didn’t change them in the default constructor, so they will have the values assigned to them by the class initialization – which occurs before the constructor.

1 Like

oh ok/