tags:

views:

208

answers:

5

I have a problem; I'm using an external library where one particular event has its own custom eventargs; with no constructor. If I want to throw my own event using these eventargs, how can I?

I'll give more detail if asked, but I'm not sure what exactly I should be giving. :)

+1  A: 

Create a new type that inherits from that EventArgs class and use that. Most likely the existing EventArgs type is abstract so you can create a new type that will inherit from it and C#'s polymorphic support will allow you to pass your new type to all methods that expect an instance of the base type.

Andrew Hare
Ah, I've already tried this. First of all; the members I wanted to set using my inherited class's constructor were private to the parent class, and secondly it wouldn't allow me to create a constructor in my inherited class.Also, the custom class isn't abstract I think, as I'm using instances of it.
Motig
+1  A: 

Use Reflector to find out how the external library instantiates it.

SLaks
A: 

You can try to obtain an instance of the class using System.Runtime.Serialization.FormatterServices. Example:

public class Foo
{
    private Foo()
    {
    }
}

...

Foo foo = (Foo)FormatterServices.GetSafeUninitializedObject(typeof(Foo));
Anthony Pegram
+1  A: 

Clearly, the designers of the library made the constructor internal to prevent you doing exactly what you're trying to do - for better or for worse. So anything you do will be a hack.

You could use Reflection to create an instance the class - see Activator.CreateInstance.

An even bigger hack might be to re-use an instance of the args object that you received and stored, but that's dangerous - who knows what internal data it might contain.

Evgeny
+5  A: 

Other answers suggest some ways (or hacks) how you could do that.

However, I'd say that if the author of the library didn't give you any way to create a new instance of their custom EventArgs class, then you shouldn't be doing that. If you want to create your own event, then you should define a new delegate and new EventArgs type (even if you were duplicating the class that is already defined in the library).

There are good reasons for this:

  • The library may change and the custom EventArgs type they provide may no longer fit your needs.
  • The library may need to pass some special object or special ID to their EventArgs, so you may not be able to create the instance correctly.

Since you can only trigger an event from a class where it is defined, you're probably defining a new event in the class (using the event keyword), so there is no real reason why you couldn't declare your own delegate. Or could you provide more details on how are you triggering the event?

Tomas Petricek