Darren Cook
Darren Cook

Reputation: 28913

Is casting from MyObject[] to Object[] and then back again a bad code smell?

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().

Upvotes: 0

Views: 125

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

How about using generics?

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

Upvotes: 4

Related Questions