I want to create an interface with a method GetId(). Depending on the subitems, it could either be an int, string or something else. This is why I tried with return type object (but then I can't specify the type in the subitems) and wanted to try with generics.
How can I do this?
What I already have:
public interface INode : IEquatable<INode>
{
object GetId();
}
public class PersonNode : INode
{
object GetId(); //can be int, string or something else
}
public class WorkItemNode : INode
{
int GetId(); //is always int
}
Thank you!
You're almost there, just define your interface using INode<T>
public interface INode<T> : IEquatable<INode<T>>
{
T GetId();
}
public class PersonNode : INode<string>
{
public bool Equals(INode<string> other)
{
throw new NotImplementedException();
}
public string GetId()
{
throw new NotImplementedException();
}
}
public class WorkItemNode : INode<int>
{
public int GetId()
{
throw new NotImplementedException();
}
public bool Equals(INode<int> other)
{
throw new NotImplementedException();
}
}
You could even use an object
with the interface
public class OtherItemNode : INode<object>
{
public bool Equals(INode<object> other)
{
throw new NotImplementedException();
}
public int Id { get; set; }
public object GetId()
{
return Id;
}
}
Either change INode
interface to a generic type interface INode<out T>
as suggested by other answers.
Or if you don't want that, implement your non-generic interface explicitly and supply a type-safe public method as well:
public class WorkItemNode : INode
{
public int GetId() //is always int
{
...
// return the int
}
object INode.GetId() //explicit implementation
{
return GetId();
}
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With