Angela
Angela

Reputation: 3389

How can I automatically create a sub class in C#?

I have the following code:

public class Page {
    public string FilePath { get; set; }
    public int RoleNumber { get; set; }
    public class Navigation {
        public string Menu { get; set; }
        public string Breadcrumbs { get; set; }
    }
}

I always need the Navigation class every time a new instance of a Page class is created. Is there a way I can have the Navigation class automatically created?

Upvotes: 0

Views: 133

Answers (1)

McGarnagle
McGarnagle

Reputation: 102743

Looks like it would be best to use inheritance in this case. You don't want to get into a situation with redundant code.

public class Navigation {
    public string Menu { get; set; }
    public string Breadcrumbs { get; set; }
}

public class Page : Navigation {
    public string FilePath { get; set; }
    public int RoleNumber { get; set; }    
}

Alternatively, you could instantiate an instance of Navigation in Page's constructor:

public class Page {
    public Navigation PageNavigation { get; private set; }
    public string FilePath { get; set; }
    public int RoleNumber { get; set; }    

    public Page() {
        PageNavigation = new Navigation();
    }

    public class Navigation {
        public string Menu { get; set; }
        public string Breadcrumbs { get; set; }
    }
}

Upvotes: 2

Related Questions