Reputation: 6619
I have a problem where I have two implemention that I want to share a interface, but they will have different types for "the same parameter", see one Guid
and one Int
.
For example:
public Class1 : IGetObject {
GetObjectBy(int Id);
}
public Class2 : IGetObject {
GetObjectBy(Guid Id);
}
At the other end of the application the "Id" argument will come from a user input which is string. So I also have
public GetObjectMethod(){
string id = dropdown.SelectedItem.Text;
IGetObject GetObject = Shared.Instance.GetObject;
var result = GetObject.GetObjectBy(id);
}
How can I make the implemention share the interface so I don't have to change something in the GetObjectMethod?
What I think is maybe an idea is to create a new type like this and declare that in the common interface. In that way the implemention know which propery it should use:
public class ObjectId(){
public ObjectId(string id){
if(Guid.TryParse(id)){
/// Figure out what value that should be set
}
}
public Guid ObjectIdAsGuid;
public Int ObjectIdAsInt;
}
What is the best way of doing it?
Upvotes: 3
Views: 586
Reputation: 1593
Create a base class for your ID, which combine both ID types to one more general ID
Upvotes: 0
Reputation: 236188
You can create GetObjectBy method which accepts string (or object), and then parse (or cast) id in implementation of interface:
public Class1 : IGetObject {
public Foo GetObjectBy(string Id)
{
var id = Int32.Parse(Id);
//...
}
}
public Class2 : IGetObject {
public Foo GetObjectBy(string Id)
{
var id = new Guid(Id);
//...
}
}
Upvotes: 4
Reputation: 152501
I want to share a interface, but they will have different types for "the same parameter"
One way to do that is to make the interface generic:
public interface IGetObject<T>
{
void GetObjectBy(T Id);
}
public class Class1 : IGetObject<int> {
void GetObjectBy(int Id);
}
public class Class2 : IGetObject<Guid> {
void GetObjectBy(Guid Id);
}
Otherwise you'd need two overloads, but each class will have to implement both functions:
public interface IGetObject
{
void GetObjectBy(int Id);
void GetObjectBy(Guid Id);
}
public class Class1 : IGetObject {
void GetObjectBy(int Id);
void GetObjectBy(Guid Id);
}
public class Class2 : IGetObject<Guid> {
void GetObjectBy(int Id);
void GetObjectBy(Guid Id);
}
Upvotes: 3