Share via


Writing Indexers in J#...

In my last post I didn't mentioned that in J# also one can write indexers, as you can write them in C#. In C#, there is a unique syntax to write indexers but in J# it is as good as writing any other property. To convert a property into indexer of a class you have to do following things extra...

  • Suppose you want to convert property "Foo" into indexer of your class then you need to apply following attribute to your class…

            @attribute System.Reflection.DefaultMember("Foo")

  • You need to add one extra parameter of int type to the property which is to be used as index.

Let’s have a look at an example to make the things crystal clear :).

Following is my indexer written in J#...

/** @attribute System.Reflection.DefaultMember("Counting")

 */

public class Program

{

     

      private String Array[] = { "First", "Second", "Third"};

      /** @property

      */

      public String get_Counting(int index)

      {

            return Array[index];

      }

      /** @property

      */

      public void set_Counting(int index, String Value)

      {

            Array[index] = Value;

      }

}

In the above snippet,

  1. I have declared property “Counting”. To make it an indexer of this class, I have set it the default member of the class by specifying it’s name in the DefaultMember Attribute. Please note following line in the code…

@attribute System.Reflection.DefaultMember("Counting" )

  1. I have added one extra int parameter to the property declaration. This parameter is the actual index you specify when you use this indexer. Note following lines in declaration of setter and getter…

public String get_Counting(int index)

public void set_Counting(int index, String Value)

Now if you want to consume this indexer in C#, then you are all set to use it like any other indexer declared in C# itself. Following code snippet shows how to use above declared indexer in C#...

class Program

    {

      

        static void Main(string[] args)

        {

ConsoleApplication2.Program prg = new ConsoleApplication2.Program();

   prg[0] = "HI";

            String x = prg[0];

         int i = 0;

        }

  }

Note following lines of code in above snippet…

prg[0] = "HI";

            String x = prg[0];

I declared "Counting" property in J# using J# syntax but I am able to consume it in C# in C# syntax.

For J# properties i would like to recommend you to read this white paper written by our very own Program Manager Pratap Lakshman.

Thanks.