Search code examples
c#fodyfody-propertychanged

Is there any way to "tell" IntelliSense and compiler that class implements the interface without actually implementing it?


I use Fody.PropertyChanged and Fody.Validar in my C# project to avoid writing boilerplate code. Let's presume I've got some class A:

[AddINotifyPropertyChanged]
[InjectValidation]
public class A { }

I have to use objects of type A in other parts of my code which require type A to implement interfaces like INotifyPropertyChanged or INotifyDataErrorInfo. There are two known ways to do it:

  1. Implement interfaces manually (a lot of boilerplate):
[AddINotifyPropertyChanged]
[InjectValidation]
public class A: INotifyPropertyChanged, INotifyDataErrorInfo { ... }
  1. Cast object of type A to required interfaces (more code, ReSharper generates warnings about suspicious casts, generic methods may break):
public static T DoSomething<T>(T arg) where T: INotifyPropertyChanged { ... }
var a = new A();
var b = DoSomething((INotifyPropertyChanged) a) // Returns INotifyPropertyChanged.

Is there any way to "tell" IntelliSense and compiler that the class implements the interface without actually implementing it and let Fody do that work?

[AddINotifyPropertyChanged]
[InjectValidation]
[Implements(typeof(INotifyPropertyChanged))]
public class A { }
var a = new A();
var b = DoSomething(a) // Returns A.

Solution

  • What exactly and why do you want from the compiler?

    It has no idea of what is going to be added post-compilation. So you are asking for a way to break one of the compiler's rules so that some casts wouldn't look shady. There is no clean way of doing it.

    The cast operation is your only way. No one but you knows that some class will suddenly implement something, regardless of what it does at the compile-time.

    ReSharper rules can be turned off, if they worry you too much.