Skip to content

Constructor Argument Value

Constructors should have "ConstructorArgument" parameters.

What does this mean ?

When developing a custom Markup Extension in WPF that accepts parameters, the ConstructorArgument markup must be utilized to indicate the discrete attributes that correspond to these arguments. However, because this is done through a string, the compiler will not catch any mistakes.

What can happen ?

This rule throws an exception if the string supplied to ConstructorArgumentAttribute does not match any constructor parameter.

Recommendation

The constructor parameter string must be written accurately because the compiler will not notice a typo.

Sample Code

Vulnerable :

using System;

namespace myLibrary
{
  public class MyExtension : MarkupExtension
  {
    public MyExtension() { }

    public MyExtension(object value1)
    {
      Value1 = value1;
    }

    [ConstructorArgument("value2")]   // Noncompliant
    public object Value1 { get; set; }
  }
}

Non Vulnerable :

using System;

namespace myLibrary
{
  public class MyExtension : MarkupExtension
  {
    public MyExtension() { }

    public MyExtension(object value1)
    {
      Value1 = value1;
    }

    [ConstructorArgument("value1")]
    public object Value1 { get; set; }
  }
}

References