2

I have a class called AlertDialogViewModel with two constructors, one taking an Object and a string and another taking two strings.

public class AlertDialogViewModel
{
    public AlertDialogViewModel(object contentObject, string title)
    {
        this.ContentObject = contentObject;
        this.Title = title;
    }

    public AlertDialogViewModel(string contentString, string title)
    {
        this.ContentString = contentString;
        this.Title = title;
    }

    public object ContentObject { get; set; }

    public string ContentString { get; set; }

    public string Title { get; set; }
}

In a unit test, I create a new instance with the first parameter being null.

    [TestMethod]
    public void Instancing_string_alert_with_null_content_throws_exception()
    {
        // Arrange
        const string title = "Unit Test";

        // Act
        var alertDialog = new AlertDialogViewModel(null, title);
    }

When I run the unit test, it uses the constructor that takes a string as a first parameter. What is the compiler/runtime doing to determine that is the correct constructor that needs to be used?

This isn't causing any issues with my code, I am just wanting to understand why that constructor is selected in the event that in the future this actually does matter.

Johnathon Sullinger
  • 7,097
  • 5
  • 37
  • 102
  • In C#, `string` is a reference type, not a value type. Therefore, a `string` can be null – Icemanind Dec 19 '14 at 18:06
  • 2
    It's because `string` is considered more specific than `object`. – juharr Dec 19 '14 at 18:07
  • Note also than you can explicitly cast `null` using `(T)null` or `null as T` to resolve issues like these explicitly – David Dec 19 '14 at 18:08
  • So the 2nd constructor is invoked only because it's more specific? What if I have the constructors first type `Person` and `Car`. How does it infer which constructor to pass null to? – Johnathon Sullinger Dec 19 '14 at 18:38
  • juharr is right. If one overload takes `Person`, and another takes `Car`, and both these types are reference types, and neither is more specific than the other, and these are the only two (relevant) overloads, then a binding-time error occurs if the argument is a "naked" `null`. – Jeppe Stig Nielsen Dec 19 '14 at 22:44

0 Answers0