Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Aug 5th, 2012  |  syntax: None  |  size: 1.80 KB  |  hits: 12  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. One Constructor for a Class and its Nested Classes
  2. class Room
  3. {
  4.     public string Name;
  5.     public int Width;
  6.     public int Height;
  7.     // and so on...
  8.  
  9.     public class Suspect
  10.     {
  11.         public string Name;
  12.         public bool PlaysCroquet;
  13.     }
  14.  
  15.     public class Weapon
  16.     {
  17.         public string Name;
  18.         public bool IsShiny;
  19.     }
  20. }
  21.        
  22. public Room(string Name, int Width, int Height)
  23. {
  24.     this.Name = Name;
  25.     this.Width = Width;
  26.     this.Height = Height;
  27. }
  28.        
  29. Room[i] = new Room("Conservatory", 7, 3);
  30.        
  31. Room[i] = new Room("Library", 8, 5, "Professor Plum", false, "Candlestick", true);
  32.        
  33. public class Room
  34. {
  35.     public Room(Suspect suspect, Weapon weapon)
  36.     {
  37.         SuspectInRoom = suspect;
  38.         WeaponInRoom = weapon;
  39.     }
  40.  
  41.     public Suspect SuspectInRoom { get; set; }
  42.     public Weapon WeaponInRoom { get; set; }
  43. }
  44.  
  45. // Example usage:
  46.  
  47. Suspect coronelCustard = new Suspect("Coronel Custard");
  48. Weapon musket = new Weapon("Musket");
  49.  
  50. Room someRoom = new Room(coronelCustard, musket);
  51.  
  52. // Then your room can be used to access all sorts of data.
  53.  
  54. Console.WriteLine(someRoom.SuspectInRoom.Nickname); // "The Big Kahuna"
  55. Console.WriteLine(someRoom.WeaponInRoom.AttackDamage); // "20"
  56.        
  57. Room someRoom = new Room(new Suspect("Colonel Custard"), new Weapon("Musket"));
  58.        
  59. var room = new Room { Name = "Library",
  60.                          Width = 7,
  61.                          Height = 3,
  62.                          Suspect = new Suspect { Name = "Professor Plum",
  63.                                                  PlaysCroquet = false },
  64.                          Weapon = new Weapon { Name = "Candlestick",
  65.                                                IsShiny = true }
  66.                         };
  67.        
  68. Room[i] = new Room("Library", 8, 5, new Suspect("Professor Plum", false), new Weapon("Candlestick", true));