Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare generic event for generic delegate in c#

Tags:

c#

.net

I have a user control which deals with fileupload. I have defined a delegate as follows

public delegate void FileUploadSuccess<T>(T value,FileUploadType F)

value can be a string as well as byte array. FileUploadType is an enum which tells which type of file was uploaded.

Now I have declared a event in usercontrol to raise this.

public event FileUploadSuccess<string> successString;   //In case I want a file name

public event FileUploadSuccess<Byte[]> successStringImage;  // In case I want a byte[] of uploaded image

What I wanted was a generic event

public event FileUploadSuccess<T> successString. 
like image 498
Rohit Raghuvansi Avatar asked Jun 27 '10 08:06

Rohit Raghuvansi


2 Answers

Except as part of generic types (i.e.

class Foo<T> { public event SomeEventType<T> SomeEventName; }

) there is no such thing as generic properties, fields, events, indexers or operators (only generic types and generic methods). Can the containing type here be generic?

like image 195
Marc Gravell Avatar answered Sep 22 '22 18:09

Marc Gravell


To the outside world, an event in many ways looks like a field of the class. Just as you can't use an open generic type to declare a field, you can't use an open generic type to declare an event.

If you could leave the type open, then the compiler would have to compile in the event handler add and remove code for every possible type for your generic parameter T. A closed generic type can't be JIT compiled, because your event is not a type in its own right, rather is a part of an enclosing type.

like image 26
David M Avatar answered Sep 22 '22 18:09

David M