-2

We may access the last index of a list/array by the following:

var l = new List<string> {"1", "2a", "3cd"};
Console.WriteLine(l[^1]);

output: "3cd"

May I know if it is possible to cast the string ^1 to index object: (second line is not working)

var s = "^1"
var index = (Index) s;
Console.WriteLine(l[index]);

To get the output: "3cd"

lrh09
  • 557
  • 4
  • 13
  • you can simply use _Linq_ using `Last()` [Last](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.last?view=net-7.0) – styx Nov 16 '22 at 07:58
  • Yea, I know that but I am trying to access the `^1` from a json file and would like to parse it, so it is not what I am looking for – lrh09 Nov 16 '22 at 07:59
  • https://learn.microsoft.com/en-us/dotnet/csharp/tutorials/ranges-indexes – Jodrell Nov 16 '22 at 08:00
  • 2
    @lrh09 then write a custom serializer which will read the value of properties with the attribute as an object, With the information you've provided it's unclear why you would want this. – CthenB Nov 16 '22 at 08:02
  • You can't. You'd have to provide your own logic to parse the `string`, specifically checking whether it starts with `'^'`. – jmcilhinney Nov 16 '22 at 08:09
  • You could compile the string in the runtime, however, don't! https://stackoverflow.com/questions/826398/is-it-possible-to-dynamically-compile-and-execute-c-sharp-code-fragments – Jodrell Nov 16 '22 at 08:24

1 Answers1

3

To instantiate an Index for one from the end, do this.

var index = new Index(1, true);

or

var index = Index.FromEnd(1);

var s = "^1"

just makes a string that uses the '^' char, that can be used in code, to indicate an Index from end.

There is no conversion, explicit or implicit between string and Index.


If, for some reason you wanted to read a Index struct from JSON, you could store both,

 int value

and the optional

 bool fromEnd = false

and use those to instantiate a new instance. This would be simpler than writing a parser for strings that contain index expressions.

Jodrell
  • 34,946
  • 5
  • 87
  • 124