Search code examples
c#wpf

Generate compile-time error for a particular constructor overload invocation


Is it possible to generate a compile-time warning/error if a particular overload of the constructor is accessed anywhere in entire solution?

Detail

This is a WPF desktop (.NET 7) project. My Pages and UserControls use d:DataContext="{d:DesignInstance Type=vm:UnderlyingVM}" feature to take advantage of design-time intellisense. However, the underlying VMs require passing in external services (standard IoC/DI stuff) in their constructors, while the designer can invoke parameter-less constructors only.

To get around this problem, I have defined parameter-less constructor overloads in each VM. Sole purpose and usage of these overloads is the designer support and these overloads must not inadvertently be called from anywhere else. Is there a way to generate a compile-time warning/error if such an invocation is found anywhere in the regular code?

One approach that I thought of was use the following in the parameter-less constructor:

if (!System.ComponentModel.DesignerProperties.GetIsInDesignMode(new DependencyObject()))
{
  #error ("This constructor can only be invoked from the WPF designer.");
}

Unfortunately, the VM layer is a .NET Standard 2.0 project and therefore cannot reference .NET 6/7 assemblies. Can anyone suggest an alternate approach?


Solution

  • You could use the ObsoleteAttribute:

    public class Example
    {
       [Obsolete("this constructor should only be used by the WPF designer")]
       public Example()
       {
       }
    }
    

    By default, if you call a method with this attribute, you will get a compiler warning.