Jules
Jules

Reputation: 671

Is there a way to create declarations using generics in C#?

I have been implementing a kind of observer pattern in c#, that goes like this:

public delegate void MyEventOccurred(MyEventArg arg);
public interface IMyEventOccurred
{
    void OnMyEventOccurred(MyEventArg arg);
}

class MyProviderClass
{
    protected MyEventOccurred OnMyEventOccurredHandler;
    public void AddMyEventOccurredHandler(MyEventOccurred handler)
    {
        OnMyEventOccurredHandler -= handler;
        OnMyEventOccurredHandler += handler;
    }

    public void RemoveMyEventOccurredHandler(MyEventOccurred handler)
    {
        OnMyEventOcurredHandler -= handler;
    } 
}

To use this class we have the following:

class MyObserverClass : IMyEventOccurred
{
    void OnMyEventOccurred(MyEventArg arg)
    {
        // Handle my event
    }

    void StartObserving(MyProviderClass provider)
    {
        provider.AddMyEventOccurredHandler(OnMyEventOccurred);
    }

    void StopObserving(MyProviderClass provider)
    {
        provider.RemoveMyEventOccurredHandler(OnMyEventOccurred);
    }
}

I'd be interested in peoples comments on whether there are improvements / better ways to do implement / expose this pattern, however my primary question is about whether there is a way to do all these declarations in a generic way, equivalent to a macro I might have created in C++.

There's a lot of code in declaring this which is completely generic, especially the naming.

In C++ I might use a macro to declare the delegate and the interface, something like:

#define DECLARE_EVENT(eventName, eventArg) \
    public delegate void eventName(eventArg arg); \
    public interface I ## eventName \
    { \
        void On ## eventName(eventArg arg); \
    }

It's clear that this hides a lot of what's going on, but it does allow quicker implementation, reduces errors and enforces consistency.

Is there some equivalent way of simplifying the implementation in C#?

Thanks

Jules

Upvotes: 0

Views: 53

Answers (2)

I.J.S.Gaus
I.J.S.Gaus

Reputation: 36

C# hasn't code generation ability. You can try realize similar behavior with help site library like a PostSharp. And i advise use for realization observer-subscriber pattern available interfaces IObserver<T> and IObservable<T> ant took a look on Reactive Extensions library.

Upvotes: 2

Stefano d&#39;Antonio
Stefano d&#39;Antonio

Reputation: 6152

You can use T4 to generate delegate and interface automatically from a list and automatically generate it on build in a similar fashion to C macros.

Upvotes: 1

Related Questions