Replace the square bracket operator of a string?

I am trying to change the behavior of a square bracket operator. Now my question is whether this is possible.

I know that I can create an extension method for String with something like this:

public static class StringExtension
{
    public static char Substring(this string value, int position)
    {
        //do something
    }
}

But how can I redefine the square bracket operator? This will not work:

public static class StringExtension
{
    public static char this[this string value, int position]
    {
        //do something
    }
}

How can I do that. Or is it possible?

+4
source share
1 answer

Let's look at a couple of concepts one at a time.

The square bracket operators are used to index into aggregate objects:

  • Arrays
  • Object Indexer Properties

They are also used to refer to attributes, but this does not apply to this answer.

, string this[...].

: " ?" : , , , , :

  • ,
  • ,
  • ,

:

  • , .
  • ,
  • System.String .

, ? , .

, , .

:

  • , ( )
  • - , .

, , , , ().

Roslyn , Extension Everything, . , .

, , , [...].

public static class StringExtension
{
    public static char CharAt(this string value, int position)
    {
        //do something
    }
}

:

string s = "Test";
char c = s.CharAt(2);
+2

Source: https://habr.com/ru/post/1663219/


All Articles