Optional parameter in an indexer - an object reference is required error

244 views Asked by At

In my OverloadedIndexer class I have a private array field called stringData, which size is set in the class constructor. I want to create an indexer with an optional parameter. It's default value should be the number of items in that array.

Unfortunately, the code line at the bottom of this post raises the following compile-time error:

An object reference is required for the non-static field, method, or property 'OverloadedIndexer.stringData'

public string this[string data, int maxOccurences = stringData.Length]

Is there a way to make it work?

2

There are 2 answers

1
Jon Skeet On BEST ANSWER

Default values have to be constants - you can't provide one which depends on another variable. So this would be fine:

public string this[string data, int maxOccurences = 0]

but what you've got isn't valid. Admittedly the error message you're getting is for a slightly different reason, but even if you could get past that, you'd run into the constness issue.

0
Grundy On

see msdn Named and Optional Arguments

Each optional parameter has a default value as part of its definition. If no argument is sent for that parameter, the default value is used. A default value must be one of the following types of expressions:

  • a constant expression;
  • an expression of the form new ValType(), where ValType is a value type, such as an enum or a struct;
  • an expression of the form default(ValType), where ValType is a value type.