Bianca
Bianca

Reputation: 21

Can I have a class within a class in C#

I have the following class:

public class NoteLink
{

    public IList<NoteLinkDetail> NoteLinkDetails
    {
        get { return _noteLinkDetails; }
    }
    private List<NoteLinkDetail> _noteLinkDetails = new List<NoteLinkDetail>();

    public NoteLink()
    {
        _noteLinkDetails = new List<NoteLinkDetail>();
    }

}

and then another class that's used just within the first class.

public class NoteLinkDetail
{
    public string L { get; set; }
    public string R { get; set; }
}

Is there anything I could do to optimize this. I DO need the second class as I use JSON to store the contents of NoteLinkDetail in a string. However is there such a thing as an inner class in C#? Any recommendation on how I could optimize this code? Thanks.

Upvotes: 0

Views: 3858

Answers (4)

Ed Swangren
Ed Swangren

Reputation: 124770

Sure; just declare the inner class from within the outer class

class NoteLink
{
    class NoteLinkDetail
    {

    }
}

Upvotes: 1

james_bond
james_bond

Reputation: 6906

Yes, you can have nested classes in C#

Upvotes: 0

NOtherDev
NOtherDev

Reputation: 9682

Yes, you can. Just nest it.

public class NoteLink
{
    // ...

    public NoteLink()
    {
        _noteLinkDetails = new List<NoteLinkDetail>();
    }

    public class NoteLinkDetail
    {
        public string L { get; set; }
        public string R { get; set; }
    }
}

Moreover, if it is not exposed outside the outer class, your inner class can even be private and stay invisible to outer class users.

Upvotes: 9

paulsm4
paulsm4

Reputation: 121849

Yes, C# allows nested classes.

C# nested classes are much more like nested classes in C++ than "inner classes" in Java. This link explains:

http://blogs.msdn.com/b/oldnewthing/archive/2006/08/01/685248.aspx

Upvotes: 3

Related Questions