Home > Software design >  Implicit conversion error C# netstandard2.1
Implicit conversion error C# netstandard2.1

Time:09-16

I'm trying to port some code from Net5.0 to Netstandard2.1, but running out of C# knowledge.

I am trying to rewrite this function

public static readonly Dictionary<Direction, CoordIJK> DirectionToUnitVector =
    Enum.GetValues<Direction>().ToDictionary(e => e, e => e switch {
        Direction.Invalid => CoordIJK.InvalidIJKCoordinate,
        _ => UnitVectors[(int)e]
    });

My attempt so far is:

public static readonly Dictionary<Direction, CoordIJK> DirectionToUnitVector =
    (Direction[])Enum.GetValues(typeof(Direction)).ToString().ToDictionary(e => e, e => e switch {   
        Direction.Invalid => CoordIJK.InvalidIJKCoordinate, 
        _ => UnitVectors[(int)e]
    });

which is giving me

Error   CS0266  Cannot implicitly convert type 'H3.Model.Direction' to 'char'. An explicit conversion exists (are you missing a cast?)  

For reference, Direction is defined as the following Enum

public enum Direction
{
    Center = 0,
    K = 1,
    J = 2,
    JK = 3,
    I = 4,
    IK = 5,
    IJ = 6,
    Invalid = 7
}

and CoordIJK.InvalidIJKCoordinate is defined as

public static readonly CoordIJK InvalidIJKCoordinate = new CoordIJK(-int.MaxValue, -int.MaxValue, -int.MaxValue);

public CoordIJK(int i, int j, int k) {
    I = i;
    J = j;
    K = k;
}

Firstly, everything after the DirectionToUnitVector is pretty much just magic symbols to me. How is the garble of code going to return a Dictionary<Direction, CoordIJK> and what can I do to fix it? I naively tried just adding (char) before Direction.Invalid to fix the error, but that didn't solve the issue.

Any help would be great.

Edit001: Added in the original code.

CodePudding user response:

The issue is that you can't use switch that way in .Net Standard

try this

using System.Linq;

public static readonly Dictionary<Direction, CoordIJK> DirectionToUnitVector =
    Enum.GetValues(typeof(Direction)).Cast<Direction>().ToDictionary(e => e, e => {
   return e == Direction.Invalid ? CoordIJK.InvalidIJKCoordinate : UnitVectors[(int)e];
});

If you add using System.Linq; and still having issues with missing ToDictionary() try rewriting it like so:

public static readonly Dictionary<Direction, CoordIJK> DirectionToUnitVector =
    System.Linq.Enumerable.ToDictionary(Enum.GetValues(typeof(Direction)).Cast<Direction>(), e => e, e => {
   return e == Direction.Invalid ? CoordIJK.InvalidIJKCoordinate : UnitVectors[(int)e];
});
  •  Tags:  
  • c# h3
  • Related