views:

124

answers:

2

I realy dont know what the problem is with VS2010. I created a class, and when I'm trying create an exemplar of the class I get an error: "Error xxx is inaccessible due to its protection level.

Example:

public class Person
{
    Person(string name, int age)
    {
        this.name = name;
        this.age = age;
    }
    public string name;
    public int age;

}

class Program
{
    static void Main(string[] args)
    {

        Person ps = new Person("Jack", 19);
    }
}
+6  A: 

Try adding the public keywork to the Person constructor:

public Person(string name, int age)
Simeon
OMG, thanks, I am ashamed.
Mishgun_
Simple solution, spot on.
Jamie Keeling
ideed this is a C++ habit to avoid "public"
Mishgun_
+6  A: 

You need to make your constructor public:

public Person(string name, int age)
{
    ...

You may ask, why aren't constructors public by default? What's the point of a class you can't instantiate via its constructor? Well, it can be useful if you want a class that can only be instantiated via factory methods, eg.

public class Person
{
    public static Person makePerson(string name, int age)
    {
        ...

The factory method, being a member of the Person class, can access the non-public constructor.

RichieHindle
thanks for explain.
Mishgun_