Thomas
Thomas

Reputation: 34188

use of c# nested class and accessiblity

i am aware of nested class. how could i design my nested class in such way that out side of parent class of nested class no one will be able to access nested class like instance create etc because i want the child class will be private. i want to expose my child class property, method everything by parent class property or method. please guide me to write the code for such kind of nested class. thanks

public class Person
{
private string _firstName;
private string _lastName;
private DateTime _birthday;

//...

public class FirstNameComparer : IComparer<Person>
{
    public int Compare(Person x, Person y)
    {
        return x._firstName.CompareTo(y._lastName);
    }
}

}

Upvotes: 1

Views: 233

Answers (3)

Robert Rouhani
Robert Rouhani

Reputation: 14678

Mark the internal class as private instead of public.

public class Person
{
    private string _firstName;
    private string _lastName;
    private DateTime _birthday;

    private FirstNameComparer firstNameComparer = new FirstNameComparer();

    public int CompareFirstNames(Person x, Person y)
    {
       return firstNameComparer.Compare(x, y);
    }

    //...

    private class FirstNameComparer : IComparer<Person>
    {
        public int Compare(Person x, Person y)
        {
            return x._firstName.CompareTo(y._lastName);
        }
    }
}

Upvotes: 7

Massimiliano Peluso
Massimiliano Peluso

Reputation: 26737

you can make the nested class private. The main class will be in charge of creating the nested class instance.

Upvotes: 2

Bonny Bonev
Bonny Bonev

Reputation: 131

You can use private accessor for nested class. If you want to expose some of its properties, you can create new property for main class like this :

private FirstNameComparer _FirstNameComparer = new FirstNameComparer();
public int Compare(Person x, Person y)
    {
        return _FirstNameComparer.Compare(Person x, Person y); 
    }

Upvotes: 1

Related Questions