Home > OS >  Converting last index string to Index object in C#
Converting last index string to Index object in C#

Time:11-17

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"

CodePudding user response:

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.

  • Related