Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top