Home > Back-end >  Cannot use interface for my generic method
Cannot use interface for my generic method

Time:04-13

I have this small bit of code that is going through a list to check for overlaps:

private List<INode> _nodes = new List<INode>();
private List<ISegment> _segments = new List<ISegment>();
public IReadOnlyList<INode> Nodes => _nodes;
public IReadOnlyList<ISegment> Segments => _segments;

private bool Overlaps<T>(ref Vector3 point, in IReadOnlyList<T> collection, out T obj) where T : INode, ISegment
{
    obj = default;
    for (int i = 0; i < collection.Count; i  )
    {
        if (collection[i].Overlaps(ref point))
            return true;
    }
    return false;
}
public bool Overlaps(ref Vector3 point, out INode node){
     return Overlaps(ref point, _nodes, out node);
}
public bool Overlaps(ref Vector3 point, out ISegment segment){
    return Overlaps(ref point, _segments, out segment);
}

The generic method can only accept two types, INode or ISegment which is what the where clause is for but i get this error :

The type 'Graphs.INode' cannot be used as type parameter 'T' in the generic type or
method 'Graph.Overlaps<T>(ref Vector3, in IReadOnlyList<T>, out T)'. There is no
implicit reference conversion from 'Graphs.INode' to 'Graphs.ISegment'.

Not sure i understand why it thinks I am converting, am I using the where keyword wrong here? Not sure how to get this working.

Interface definitions:

public interface INode{
    bool Overlaps(ref Vector3 point);
}
public interface ISegment{
    bool Overlaps(ref Vector3 point);
}

CodePudding user response:

The where keyword says that your Generic type must implement INode AND ISegment.

INode and ISegments seems to have the same contracts you can build interface inheritance based on this.

public interface INode{
     bool Overlaps(ref Vector3 point);
}
public interface ISegment : INode { }
//OR
public interface ISegment {
     bool Overlaps(ref Vector3 point);
}
public interface INode : ISegment { }
  • Related