0

I'm reviewing/refactoring some code and I met an interdependency I don't like, but I'm not sure what the best way to fix this in C# is. The essence of my question is that in one file I have:

class MyObject
{
  public string Name {get;set;}
  public int? Age {get;set;}
}

public interface IConnection
{
  void Connect(string user,string pw,Action<MyObject[]> onConnect);
  void Disconnect();
}

Then in another file:

public class ConcreteDataProvider : IConnection
{
  public void Connect(string user,string pw,Action<MyObject[]> onConnect)
  {
    //...
    IEnumerable<MyObject> collection = ...
    onConnect( collection.ToArray() );
  }
}

The issue I have with this design is that MyObject is specific to this concrete data provider. I don't want it mentioned in IConnection.

My idea was to refactor IConnection.Connect() to look like:

void Connect(string user,string pw,Action<Object[]> onConnect);

And then in the ConcreteDataProvider implementation of onConnect I will cast the array to MyObject[]. (By the looks of Unable to cast object of type 'System.Object[]' to 'MyObject[]', what gives? that means I will need to use Array.ConvertAll)

Is this a bad design that will come back to haunt me?


BTW, the call to ToArray() triggers the data download, and I don't want onConnect() called until it finishes. Behind the scenes it also triggers the actual connection; I don't know if the connection is valid and working until a first query has been performed. Which is why I don't want to pass IEnumerable to OnConnect(), and have it do the call to ToArray().

Community
  • 1
  • 1
Darren Cook
  • 27,837
  • 13
  • 117
  • 217

1 Answers1

4

How about using generics?

public interface IConnection<T>
{
  void Connect(string user, string pw, Action<T[]> onConnect);
  void Disconnect();
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Thanks for the suggestion. What are the pros/cons of this, over Object[]? – Darren Cook Nov 26 '12 at 09:58
  • Strong typing, compile-time safety, refactor friendly, no need to perform casts at runtime, ... this list goes on. – Darin Dimitrov Nov 26 '12 at 09:59
  • That is a good list of good points. The big downside to this is the difficulty I had getting it to compile! First I needed a new constraint on the MyObject class. Then the LINQ intelligence failed, and wanted me to specify the template parameters explicitly on the select call (CS0411). – Darren Cook Nov 27 '12 at 11:18