Nussti
Nussti

Reputation: 67

C# Change Method Modifier of nested Class

I want to figure out if this is possible: I have a class

class Class
{

    private Person person = new Person();
    public void NamePerson()
    {
        person.Name = "Peter";
    }

    public Person CPerson
    {
        get
        {
            return person;
        }
    }

    public class Person
    {
        public string Name { set; get; }
    }
}

Inside of Class I want to have full access of the person object. But having a write access of Person outside of Class

 Class a = new Class();
 a.CPerson.Name = "Steve"; !!!!!

should be invalid. I only want to have a read access.

string name = a.CPerson.Name;

Is there a way to do this in C#??? Thank you!

Upvotes: 2

Views: 183

Answers (1)

Kevin Gosse
Kevin Gosse

Reputation: 39007

You can use an interface for that:

public interface IPerson
{
    string Name { get; }
}

public class Person : IPerson
{
    public string Name { get; set; }
}

Now inside of class, you reference the object as Person, but only return an instance of IPerson:

class Class
{
    private Person person = new Person();
    public void NamePerson()
    {
        person.Name = "Peter";
    }

    public IPerson CPerson
    {
        get
        {
            return person;
        }
    }    
}

Upvotes: 3

Related Questions