qqqqqqq
qqqqqqq

Reputation: 2227

Specify the default value for the parameterful property in C#

How can I specify the default value for the parameterful property in C#?

While exploring the C# I come across the following excerpt in the CLR via C# book:

You can specify default values for the parameters of methods, constructor methods, and parameterful properties (C# indexers). You can also specify default values for parameters that are part of a delegate definition. Then, when invoking a variable of this delegate type, you can omit the arguments and accept the default values.

So, that excerpt led me to try out the following code:

using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace myprogram
{
    class Program
    {
        int this[int index = 0] {
            get {
                return 7;
            }
            set {

            }
        }
        static void Main(string[] args)
        {
            Program p = new Program();
            Console.WriteLine(p[]);
        }
    }
}

The code does not compile and produces the following errors:

{
    "resource": "/c:/Projects/dotNet/Console.NET/Program.cs",
    "owner": "msCompile",
    "code": "CS0443",
    "severity": 8,
    "message": "Syntax error; value expected [C:\\Projects\\dotNet\\Console.NET\\Console.NET.csproj]",
    "startLineNumber": 20,
    "startColumn": 33,
    "endLineNumber": 20,
    "endColumn": 33
}

{
    "resource": "/c:/Projects/dotNet/Console.NET/Program.cs",
    "owner": "csharp",
    "code": "CS0443",
    "severity": 8,
    "message": "Syntax error; value expected [Console.NET]",
    "source": "csharp",
    "startLineNumber": 20,
    "startColumn": 33,
    "endLineNumber": 20,
    "endColumn": 34
}

And also the following warning is produced:

{
    "resource": "/c:/Projects/dotNet/Console.NET/Program.cs",
    "owner": "csharp",
    "code": "CS1066",
    "severity": 4,
    "message": "The default value specified for parameter 'index' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments [Console.NET]",
    "source": "csharp",
    "startLineNumber": 9,
    "startColumn": 22,
    "endLineNumber": 9,
    "endColumn": 27
}

So, why can not I use the default parameter in the call: p[]? What am I missing here?

Upvotes: 0

Views: 1138

Answers (1)

René Vogt
René Vogt

Reputation: 43876

As the warning states:

...that is used in contexts that do not allow optional arguments...

C# currently has no valid syntax for ommitting the indexer value. p[] simply is not valid C#.

I don't know why the c# team allowed to define a default value if it cannot be used, but that's a question only they can answer.

Upvotes: 2

Related Questions