user3174075 user3174075 - 3 months ago 11
C# Question

Will changing interface break existing clients

Preface: This code is used within a windows desktop application, client / server application, where the server sends and receives messages to/from the client using SMessage based classes

I have the following interface

public interface IMessage
{
string ID { get; }

string R_ID { get; set; }

DateTime Send { get; }
}


Here is the concrete implementation of this interface:

[Serializable]
public class SMessage : IMessage
{
public string ID { get; set; }

public string R_ID { get; set; }

public DateTime Send{ get; set;}

public SMessage()
{
R_ID = "";
ID = Guid.NewGuid().ToString();
Send = DateTime.UtcNow;
}

public SMessage(SMessage msg)
{
ID = msg.ID;
Send = msg.UTCSend;
R_ID = msg.R_ID;
}

}


I have released software to the world using the above interface and now I need to add a piece of additional data to this interface "Where"

public interface IMessage
{
string ID { get; }

string R_ID { get; set; }

DateTime Send { get; }

string Where { get; }
}


My question : Will adding this piece of data break existing clients in the field?

If so, how I can I update the interface / concrete classes so existing clients don't break?

Thanks

Additional info:

The SMessage is the base class for other messages that are sent within the application:

public class InstallMessage : SMessage
{
}

public class ChangeState : SMessage
{
}


How can I keep from breaking existing clients?

So, if I do this:

public interface IMessage2 : IMessage
{
string Where { get; }
}


And this:

public class SMessage : IMessage2
{
// the correct implementation for IMessage2 is added and omitted here for brevity
}


So what I am unsure about is how do I handle the case where I don't know if the message is from IMessage2 or not? ( NOTE: this code is in the client and server applications )

EXISTING CODE IN THE FIELD:

public void ReceiveChange( ChangeState msg )
{
string x = msg.ID.ToString();
}


NEW CODE THAT WILL BE SENT OUT WITH NEXT VERSION:

public void ReceiveChange( ChangeState msg )
{
string x = msg.ID.ToString();

// do I need to do some converting to keep from breaking ?
IMessage2 iMsg = msg as IMessage2;
if( iMsg2 != null )
{
string y = iMsg2.Where;
}
}


Thanks

Answer

Your interface's consumers won't complain, but the implementations will.

If you want to avoid this, then create a new interface that extends from the old one:

public interface INewMessage : IMessage
{
    string Where { get; set; }
}
Comments