0

It seemed like this was possible, but I can't find a reference on how to accomplish it, though I've seen a few things that are closely related. I have a particular type of class that requires a public or private default ctor. The reason is stylistic; it is a domain aggregate and the only case where a default ctor should be used is during event store replay. There are obvious ways to work around this, but I'm trying to lock this particular type down. At any rate, what I'm hoping to do is create an attribute that can be applied at the class level that would enforce the existence of a default ctor. If one isn't found, it won't compile... or at the very least, give it the big nasty blue underline like [Obsolete()] does. I figured this was potentially doable with Roslyn. Any direction would help. The solution would ideally travel with the project rather than being something that needs to be installed on visual studio.

Sinaesthetic
  • 11,426
  • 28
  • 107
  • 176
  • 1
    Yep, sounds like a perfect use-case for Roslyn analyzers. It would be too broad for an answer so I suggest you just start looking into it: create an attribute in the solution that you will use to mark these things (though you can also omit it if you have other ways to find the types) and register an analyzer on semantic/syntax level which looks at the attributes of the types it passes and returns an error-level diagnostic when your conditions aren't met. – Jeroen Vannevel Jul 06 '17 at 21:41
  • @JeroenVannevel do you happen to know, does that analyzer travel as part of an assembly? In other words, can I create it and use it across multiple solutions? Otherwise thanks for at least confirming that I'm on the right track. – Sinaesthetic Jul 07 '17 at 20:56
  • Yes, analyzers are packaged with the solution as they are added as nuget references – Jeroen Vannevel Jul 07 '17 at 21:00

1 Answers1

1

Just a simple idea, for a public default constructor you could make use of the where T : new() constraint - even though attributes cannot be generic you can supply typeof(HasDefaultConstructor<MyClass>) as an argument to an attribute:

public static class HasDefaultConstructor<T> where T : new() { }

public class CheckAttribute : Attribute
{
    public CheckAttribute(Type type) { }
}

[Check(typeof(HasDefaultConstructor<MyClass>))]
public class MyClass
{
    public MyClass() { }
}

But it feels a bit hacky having to supply the type you're applying the attribute to, and doesn't work for the non-public constructors, but it does fail at compile-time without needing any addons.

C.Evenhuis
  • 25,996
  • 2
  • 58
  • 72
  • Thanks; I had a similar idea, but I really don't want these domain aggregates to have a public ctor. I was hoping to possibly solve this problem while also learning about more about roslyn features – Sinaesthetic Jul 07 '17 at 20:58