Skip to content

Instantly share code, notes, and snippets.

@ScottLilly
Created February 5, 2018 17:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ScottLilly/e39bdefb25d7226832bb4a29a6e39826 to your computer and use it in GitHub Desktop.
Save ScottLilly/e39bdefb25d7226832bb4a29a6e39826 to your computer and use it in GitHub Desktop.
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