Hello everyone,
It's the first time I publish something in the forum, so I apologize if the code is not presented in the appropriate font for a code.. :/
I tried to implement the decorator design pattern, but for some reason something goes wrong during the process and the compiler throws NullReferenceException for a reason I can't figure out.
I'd be grateful for your help.
I have this as my basic item:
- public class Hambruger
- {
- public virtual int PattySizeInGrams { get; set; }
- public virtual string Bun { get; set; }
- public Hambruger()
- {
- PattySizeInGrams = 200;
- Bun = "Ordinary bun";
- }
- }
- public virtual void GetDescription()
{
Console.WriteLine("Hamburger:\n {0}, {1} grams", Bun,PattySizeInGrams );
}
this is the abstract decorator class:
- public abstract class HamburgerDecorator : Hambruger
- {
- protected Hambruger hamburgerToBeDecorated;
-
- public HamburgerDecorator(Hambruger theHamburger)
- {
- hamburgerToBeDecorated = theHamburger;
- }
- public override string Bun
- {
- get
- {
- return hamburgerToBeDecorated.Bun;
- }
-
- set
- {
- hamburgerToBeDecorated.Bun = value;
- }
- }
- public override int PattySizeInGrams
- {
- get
- {
- return hamburgerToBeDecorated.PattySizeInGrams;
- }
-
- set
- {
- hamburgerToBeDecorated.PattySizeInGrams = value;
- }
- }
- }
This is the concrete decorator class:
- public class ExtraMeatDecorator : HamburgerDecorator
- {
- public ExtraMeatDecorator(Hambruger hamburgerToDecorate) : base(hamburgerToDecorate) { }
- public override void AddExtraMeat()
- {
- hamburgerToBeDecorated.PattySizeInGrams += 100;
- }
- }
And this is my Main:
- class Program
- {
- static void Main(string[] args)
- {
- Hambruger ham = new Hambruger();
- Hambruger decorated = new ExtraMeatDecorator(ham);
- }
- }
The exception happens when "new
ExtraMeatDecorator(ham) is called. Before it calls the ExtraMeatDecorator constructor, it has to call its base constructor -
HamburgerDecorator, which in turn, has to call first to the Hamburger constructor. The PattySizeInGrams
and Bun properties are null and thus, cannot make the assignment in the Hamburger constructor.
I just can't seem to figure out the reason. I've made a simpler example in which this problem didn't happen:
- public class Parent
- {
- public int Age { get; set; }
- public Parent()
- {
- Age = 25;
- }
- }
-
- public class Child : Parent
- {
- public Child(Parent par) : base() { }
- }