I am trying to create forms that inherit from a "generic" base class where the generic argument of that base class has a constraint that it must implement one of my interfaces.
It compiles and runs just fine. My problem is with the Visual Studio designer. It will open the form fine until I rebuild the project, after which it then reports the error below when trying to view the form designer until such time as I either restart Visual Studio, or remove the custom interface constraint in the base class.
GenericArguments[0], 'InterfaceInBaseClassProblem.TestEntity', on 'InterfaceInBaseClassProblem.BaseWindowClass`1[EntityType]' violates the constraint of type 'EntityType'.
Step 1: Create an interface
namespace InterfaceInBaseClassProblem
{
public interface ITestInterface
{
void Func1();
}
}
Step 2: Create a class that implements the interface
namespace InterfaceInBaseClassProblem
{
public class TestEntity : ITestInterface
{
public void Func1()
{
}
}
}
Step 3: Create a generic base class Form that requires a generic parameter constrained to require an implementation of the interface we created
using System.Windows.Forms;
namespace InterfaceInBaseClassProblem
{
public class BaseWindowClass<EntityType> : Form where EntityType : ITestInterface
{
}
}
Step 4: Now create a new form that inherits from our Generic Base Form and uses the TestEntity class as the parameter
namespace InterfaceInBaseClassProblem
{
public partial class Form1 : BaseWindowClass<TestEntity>
{
public Form1()
{
InitializeComponent();
}
}
}
Step 5: Save your project and test for the following behaviour that I am trying to work around or solve:
a) Close Visual Studio
b) Open Visual Studio
c) Open the Form1 class to view its designer and confirm its working
d) Close the Form1 designer you just opened
e) Rebuild the project
f) Open the Form1 class to view the error I have reported.
g) Either restart Visual Studio, or comment out the "where EntityType : ITestInterface" constraint we included with step 3 and rebuild to see it start working again
Additional Notes:
- I have tested in VS2015 and 2017 with the same results
- I have tested on multiple development machines
- My need for this design is in the base class and various additional functions / roles it will perform that require a generic "EntityType" and require it can perform the actions I add to my custom interface(s). These generic functions will be used by all forms I declare to inherit from this base class.