I'm a newbie in C# and would like to know if, having two classes in the same namespace, I can call a constructor of one in a constructor of the other one?
For example:
class Company
{
// COMPANY DETAILS
Person owner;
string name, website;
Company()
{
this.owner = new Person();
}
}
The above returns "Person.Person()" is inaccessible due to its protection level. Person class looks like this:
class Person
{
// PERSONAL INFO
private string name, surname;
// DEFAULT CONSTRUCTOR
Person()
{
this.name = "";
this.surname = "";
}
}
Is there anything I'm missing here? Shouldn't the constructor be accessible from wherever in the same namespace?
You defined the constructor as private hence you cannot access it.
The compiler even gives you a hint:
error CS0122: 'Person.Person()' is inaccessible due to its protection level
The C# 6.0 specification state for access modifiers:
When a class_member_declaration does not include any access modifiers, private is assumed.
whereas a class_member_declaration is specified as
class_member_declaration
: ...
| constructor_declaration
| ...
;
Only default constructors are public by default when the class is not defined as abstract.
Therefore change
Person() { }
to
public Person() { }
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments