WDUK
WDUK

Reputation: 1524

Can't seem to cast from interface to my struct for a list

I have a function that returns a list of an interface called IPathfindingNode.

I created a struct that implements the interface:

public struct Node : IPathfindingNode
{
    public int X { get; }
    public int Y { get; }
}

I call a function that returns a list of the interface:

public List<IPathfindingNode> FindPath(Vector2Int startPoint, Vector2Int targetPoint)

When i try to assign the result i get an error saying i cannot assign it to my list, but i do not understand why.

List<Node> path = Map.FindPath(startPoint, targetPoint);

I get this error:

Cannot implicitly convert type 'System.Collections.Generic.List<Pathfinding.IPathfindingNode>' to 'System.Collections.Generic.List<Grids.Node>'

How do i cast this correctly ? I tried as List<Node>(); but still would not correctly convert.

Upvotes: 0

Views: 210

Answers (1)

TheGeneral
TheGeneral

Reputation: 81503

Disregarding any other problem, you could just use Cast

Casts the elements of an IEnumerable to the specified type.

List<Node> path = Map.FindPath(startPoint, targetPoint)
                     .Cast<Node>()
                     .ToList()

If FindPath returns other non Node implementations of IPathfindingNode you could use OfType

Filters the elements of an IEnumerable based on a specified type.

Upvotes: 4

Related Questions