Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create generic property in interface

Tags:

c#

.net

asp.net

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!

like image 760
casaout Avatar asked Jul 24 '13 06:07

casaout


2 Answers

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;
    }
}
like image 34
Ed W Avatar answered Oct 01 '22 01:10

Ed W


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();
    }

    ...
}
like image 184
Jeppe Stig Nielsen Avatar answered Oct 01 '22 02:10

Jeppe Stig Nielsen