Skip to content

Instantly share code, notes, and snippets.

@ScottLilly ScottLilly/Flooring.cs Secret
Created Feb 5, 2018

Embed
What would you like to do?
Demonstration code for classes with properties that are other classes
namespace PropertyExample
{
public class Flooring
{
public string Material { get; set; }
public string Color { get; set; }
public Flooring(string material, string color)
{
Material = material;
Color = color;
}
}
}
using System.Collections.Generic;
namespace PropertyExample
{
public class House
{
public List<Room> Rooms { get; set; } = new List<Room>();
}
}
namespace PropertyExample
{
public class Room
{
public string Name { get; set; }
public Flooring Floor { get; set; }
public Room(string name, Flooring flooring)
{
Name = name;
Floor = flooring;
}
}
}
using System.Collections.Generic;
namespace PropertyExample
{
public class Test
{
private readonly House _testHouse = new House();
// Contructor, populates the class-level _testHouse variable
public Test()
{
// Create variables for each type of flooring
Flooring brownCarpet = new Flooring("Carpet", "Brown");
Flooring whiteCarpet = new Flooring("Carpet", "White");
Flooring orangeTile = new Flooring("Tile", "Orange");
Flooring darkBrownWood = new Flooring("Wood", "Dark Brown");
// Populate the houuse with rooms (with flooring)
_testHouse.Rooms.Add(new Room("Kitchen", orangeTile));
_testHouse.Rooms.Add(new Room("Living Room", whiteCarpet));
_testHouse.Rooms.Add(new Room("Dining Room", darkBrownWood));
_testHouse.Rooms.Add(new Room("Master Bedroom", brownCarpet));
_testHouse.Rooms.Add(new Room("Guest Bedroom", brownCarpet));
}
public List<Room> GetRoomsWithBrownCarpet()
{
List<Room> roomsWithBrownCarpet = new List<Room>();
foreach(Room room in _testHouse.Rooms)
{
if(room.Floor.Material == "Carpet" && room.Floor.Color == "Brown")
{
roomsWithBrownCarpet.Add(room);
}
}
return roomsWithBrownCarpet;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.