Main Page
 The gatekeeper of reality is
 quantified imagination.

Stay notified when site changes by adding your email address:

Your Email:

Bookmark and Share
Email Notification
Working with Nested Classes
Purpose
This purpose of this brief tutorial is to show how (this example was put together in Visual Studio 2022, MVC C#) to work with nested modeled class data in C#, a process that has been simplified over time.

You may be surprised how easy it is nowadays:

The Model Class in a Model Class:
public class Parent {
	public string SomeName { get; set; } = string.Empty;
	public List<Child> childElements { get; set; } = new List<Child>();
	public class Child {
		public string SomeTitle { get; set; } = string.Empty;
	}
}


Prepping Data for the Child Class:
List<Parent.Child> childData = new List<Parent.Child>();
childData.Add(new Parent.Child { SomeTitle = "Lit Title"; });
childData.Add(new Parent.Child { SomeTitle = "Less Lit Title"; });


Adding Data to the Parent Class:
List<Parent> control = new List<Parent>();
control.Add(new Parent() {
	SomeName = "Random Name",
	childElements = new List<Parent.Child>(childData)
});


Reading the Parent and Child List Data:
foreach (var parentData in control) {
	string someName = parentData.SomeName;
	Console.WriteLine("SomeName = {0}", someName);
	foreach (var childElement in parentData.childElements) {
		string someTitle = childElement.SomeTitle;
		Console.WriteLine("------ SomeTitle = {0}", someTitle);
	}
}


About Joe
Find Out Now!