Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I cannot extend (subclass) DataReceivedEventArgs?

I'm trying to extend DataReceivedEventArgs so that I can pass in additional data to a class that is extending Process. Pretty much rather than just get Data from a process when hooking up to Process.OutputDataReceived, I would like to pass in a control for it to write to.

When trying to extend DataReceivedEventArgs I get errors:

The type 'System.Diagnostics.DataReceivedEventArgs' has no constructors defined

public class DataReceivedArgsWithControl : DataReceivedEventArgs
{
    public Control ControlAdded { get; set; }
}

How can I add another property to this Args? I've extended EventArgs itself because it has a constructor, but not sure how to extend this Args.

like image 487
5StringRyan Avatar asked Sep 03 '26 02:09

5StringRyan


1 Answers

I suspect that you can't because the constructor is Internal. Perhaps a better approach would be to wrap the DataReceivedEventArgs inside your EventArgs derived class.

class MyDataReceivedEventArgs : EventArgs
{
   DataReceivedEventArgs _inner;

   public MyDataReceivedEventArgs(DataReceivedEventArgs inner, object extraProperty)
   {
      _inner = inner;
      ExtraProperty = extraProperty;
   }

   public object ExtraProperty { get; private set;}
   public DataReceivedEventArgs DataArgs  
   { 
     get
     {
        return _inner;
     }
   }
}

Of course, this might not be suitable if you need the polymorphism with DataReceivedEventArgs. If you have an event handler that is expecting a DataReceivedEventArgs then it won't work with the wrapper class. For example:

public void MyHandler(object sender, DataReceivedEventArgs e) { ... }

This could only receive a DataReceivedEventArgs instance or an instance of a derived type, which your wrapper is not. So it depends if you need to treat your custom EventArgs class is if it were a DataReceivedEventArgs anywhere.

UPDATE-

If you can't change the signature of the delegate you're using from public delegate void DataReceivedEventHandler(object sender, DataReceivedEventArgs e) then you can still subscribe using a method with the signature void MyEventHandler(object sender, EventArgs e) thanks to contravariance of delegate parameters and then check the actual type of the EventArgs parameter.

public void MyEventHandler(object sender, EventArgs e)
{
   var dataEventArgs = e as MyDataReceivedEventArgs;

   if(dataEventArgs != null
   {
      var extendedProperty = dataEventArgs.ExtraProperty;
      var innerArgs = dataEventArgs.DataArgs;
   }
}

The ideal option would be to redefine the delegate type to match your wrapper, but the above approach will work.

like image 176
Steve Rowbotham Avatar answered Sep 05 '26 16:09

Steve Rowbotham



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!