2

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.
K. Voroncov
  • 189
  • 1
  • 11
  • How would you guarantee that the interface contract is on type A? – vsarunov May 24 '19 at 11:00
  • From theirs example at https://github.com/Fody/PropertyChanged . You need to specify that `A` implements `INotifyPropertyChanged`, `class A: INotifyPropertyChanged` – Renat May 24 '19 at 11:01
  • I can't think of any way. Your only option is to either actually implement the interface or have a base class implementing it in virtual functions maybe – Patrick Hollweck May 24 '19 at 11:04

1 Answers1

2

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.

AgentFire
  • 8,944
  • 8
  • 43
  • 90
  • I note that some Fody packages work-around this by having dummy extension-methods and empty marker-interfaces so the C# syntax checker in VS won't complain about methods that don't exist yet, for example. Other code-generation techniques using Roslyn do work with IntelliSense because they generate actual C# code (instead of IL) in the `obj` directory (just like how XAML `.designer.cs` files work in WPF). Both approaches feel like hacks to me, but they work! – Dai Apr 20 '20 at 09:19
  • @Dai Well, if you're still interested, I've heard about this Source Generators thingy for C#. Look it up. – AgentFire Feb 10 '22 at 10:06