Home:ALL Converter>Why must I have both an access modifier and a constructor in C#?

Why must I have both an access modifier and a constructor in C#?

Ask Time:2015-04-24T04:23:05         Author:Aspiring Coder 2.0

Json Formatter

In a simple program below, why must define it as private first and then make a constructor? I think I think I understand it's first made private because you don't want it to be changed (I think) and then you define it again in public so it can be viewed in different classes, but why must I name it differently?

I tried to ask for help elsewhere and they said "in C you need a constructor for variables of a class with default parameters to initialize it. so when you run it in your main application the compiler knows what it is." But I'm not really sure what that means. It seems quite a bit complicated.

class Name
{
       private String first, middle, last;
       public Name(String fname, String mname, String lname)
       {
             first = fname;
             middle = mname;
             last = lname;
        }
 }
 class Program
 {
       static void Main(String[] args)
       {
           Name myName = new Name("John", "Richard", "Smith");

        }
  }
}

Author:Aspiring Coder 2.0,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/29833606/why-must-i-have-both-an-access-modifier-and-a-constructor-in-c
JeffFerguson :

The private keyword means that the variable is not visible outside of the class in which it defined. If you were to write code in Main(), for example, that attempts to access the first, middle, or last variables, you would get an error. The variables are privately accessible only to the code in the Name class.\n\nBy contrast, the constructor is public so that it can be made visible outside of the class in which it was defined. This is why you don't receive an error when you access the constructor from the Main() method.",
2015-04-23T20:27:39
yy