Rohit Sharma
Rohit Sharma

Reputation: 6490

C# "Initializers runs from derived to base" is obvious with Unity but not otherwise

I am not sure if this is a unity bug but can anyone help me explain why the below program in the third case prints 150?

void Main()
{
// Test 1
Derived d = new Derived();
d.Height.Dump(); //Prints 10

// Test 2
IUnityContainer unityContainer = new UnityContainer();
unityContainer.Resolve(typeof(Derived)).Dump(); // Prints 10

// Test 3 
unityContainer.RegisterType<IPrintHeightService<Derived>, PrintHeightService<Derived>>();
var output = unityContainer.Resolve<IPrintHeightService<Derived>>();
output.Show(); //Prints 150
}


public interface IHasHeight
{
    Int32 Height {get; set;}
}

// Define other methods and classes here
public class Default : IHasHeight
{
    public Int32 Height {get; set;}

    public Default()
    {
        Height = 150;
    }
}

public class Derived : Default
{
    public new Int32 Height {get { return 10;}}
}


public interface IPrintHeightService<T> where T:IHasHeight, new() 
{
    void Show();
}

public class PrintHeightService<T> : IPrintHeightService<T> where T:IHasHeight, new()
{
    private IHasHeight objectWithHeight;
    public PrintHeightService(IUnityContainer unityContainer)
    {
        objectWithHeight = (T) unityContainer.Resolve(typeof(T));
    }

    public void Show()
    {
        Console.WriteLine(objectWithHeight.Height); // Prints 150
    }
}

I suspect this is because of the intializers are run from derived to base as explained (http://blogs.msdn.com/b/ericlippert/archive/2008/02/18/why-do-initializers-run-in-the-opposite-order-as-constructors-part-two.aspx) but why it is obvious with unity and not otherwise?

Thanks much.

Upvotes: 0

Views: 165

Answers (1)

Botz3000
Botz3000

Reputation: 39620

It's because you declared Height as new. By declaring it as new, Derived doesn't override Height, it just hides it. That has nothing to do with the initializers.

Which means that the new implementation doesn't have anything to do with the virtual Property declared by the Interface, it just happens to have the same name, thus "hiding" it. By calling Height over IHasHeight (in the Show() method of PrintHeightService you access a field with that type), the property declared by the interface is called, which is implemented in Default. You will only get Derived.Height, if you call it via a reference of the type Derived.

You can see for yourself: Change the type of the variable d in example 1 to Default or IHasHeight and you'll see that you will get 150, too.

If you truly want to override the implementation of Height in Derived

  • Declare Height as virtual in Default and then
  • Declare Height as override in Derived
  • And remove the new modifier.

Upvotes: 4

Related Questions