Mike
Mike

Reputation: 346

An inaccessible class. VS2010

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);
    }
}

Upvotes: 2

Views: 616

Answers (2)

RichieHindle
RichieHindle

Reputation: 281675

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.

Upvotes: 6

Simeon
Simeon

Reputation: 5579

Try adding the public keywork to the Person constructor:

public Person(string name, int age)

Upvotes: 6

Related Questions