Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call an indexer on a C# class from PowerShell?

Tags:

c#

powershell

I'm having trouble figuring out how to get Powershell to call an indexer on my class. The class looks something like this (vastly simplified):

public interface IIntCounters
{
    int this[string counterName] { get; set; }
}

public class MyClass : IIntCounters
{
    public IIntCounters Counters { get { return this; } }

    int IIntCounters.this[string counterName]
        { get { ...return something... } }
}

If I new up this class I can't just use the bracket operator on it - I get an "unable to index" error. I also tried using get_item(), which is what Reflector shows me the indexer ultimately becomes in the assembly, but that gets me a "doesn't contain a method named get_item" error.

UPDATE: this appears specific to my use of explicit interfaces. So my new question is: is there a way to get Powershell to see the indexer without switching away from explicit interfaces? (I really don't want to modify this assembly if possible.)

like image 513
scobi Avatar asked Nov 10 '10 22:11

scobi


People also ask

What is indexer in C?

Indexers allow instances of a class or struct to be indexed just like arrays. The indexed value can be set or retrieved without explicitly specifying a type or instance member. Indexers resemble properties except that their accessors take parameters.

What is the use of indexers in C#?

Indexers are a syntactic convenience that enable you to create a class, struct, or interface that client applications can access as an array. The compiler will generate an Item property (or an alternatively named property if IndexerNameAttribute is present), and the appropriate accessor methods.

Can we have static indexer in C#?

You can't make a Static Indexer in C#… The CLR can, but you can't with C#. You can't even trick the compiler with VB.NET.

What keyword is used in the syntax of an indexer?

“this” keyword is always used to declare an indexer. To define the value being assigned by the set indexer, ” value” keyword is used. Indexers are also known as the Smart Arrays or Parameterized Property in C#.


2 Answers

This works for me (uses reflection):

$obj = new-object MyClass
$p = [IIntCounters].GetProperty("Item")
$p.GetValue($obj, @("counterName"))
like image 100
dvdvorle Avatar answered Oct 20 '22 22:10

dvdvorle


I haven't tried this, but it seems like it should work:

$obj = new-object MyClass
$counters = [IIntCounters]$obj
$counters['countername']

(OK, I played around a little and I no longer think this is likely to work, but it still may be worth a try.)

like image 33
OldFart Avatar answered Oct 20 '22 21:10

OldFart