1

I am trying to create a context class that detects any changes to a property. I was able to achieve this by using the ImpromptuInterface package.

public class DynamicProxy<T> : DynamicObject, INotifyPropertyChanged  where T : class, new()
{
    private readonly T _subject;
    public event PropertyChangedEventHandler PropertyChanged;

    public DynamicProxy(T subject)
    {
        _subject = subject;
    }

    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(_subject, new PropertyChangedEventArgs(propertyName));
    }

    public static I As<I>() where I : class
    {
        if (!typeof(I).IsInterface)
            throw new ArgumentException("I must be an interface type!");

        return new DynamicProxy<T>(new T())
            .ActLike<I>();
    }

    // Other overridden methods...
}

What I would like to achieve though is for my method to return a class and not an interface.

public class Class<T>
{
    public IAuthor GetAuthor()
    {
        var author = new Author
        {
            Id = 1,
            Name = "John Smith"
        };

        var proxy = DynamicProxy<Author>.As<IAuthor>();

        return proxy;
    }
}

static void Main(string[] args)
{
    Class<Author> c = new Class<Author>();
    var author = c.GetAuthor(); // Can I do something to change this to type Author?
    author.Name = "Sample"; //This code triggers the OnPropertyChangedMethod of DynamicProxy<T>

    Console.ReadLine();
}

public interface IAuthor : INotifyPropertyChanged
{
    int Id { get; }
    string Name { get; set;  }
}

In my Class class my proxy object returns an IAuthor because that is what ImpromptuInterface requires. But is it possible for me to cast IAuthor back to Author so that the GetAuthor method returns an Author object and will still have INotifyPropertyChanged implemented?

Josh Monreal
  • 754
  • 1
  • 9
  • 29
  • Surely you can just cast your returned IAuthor to Author if Author inherits IAuthor? aka Author author = (Author)c.GetAuthor() – Chris Dixon Aug 29 '18 at 08:57
  • It does not. Is it possible though to **programmatically** inherit my `Author` object to `IAuthor`? – Josh Monreal Aug 29 '18 at 08:58
  • If Author doesn't inherit IAuthor then, to my knowledge, you're going to struggle there with the type casting. Out of options other than hacking around with the first bit of code to allow non-interfaces to be sent back from it and then use Author that way - but that's a hack. – Chris Dixon Aug 29 '18 at 09:02
  • @ChrisDixon: Is there no way to programmatically inherit the Author object to IAuthor? – Josh Monreal Aug 29 '18 at 09:03
  • not that I know of unfortunately - some guru out there well versed in Reflection may be able to help, but I'm not sure it's even possible. – Chris Dixon Aug 29 '18 at 09:36

0 Answers0