Adam Naylor
Adam Naylor

Reputation: 6330

How can this not be a constant value?

I know this is probably just a terminology mismatch but if i'm not mistaken i believe c# is? unless i'm missing something obvious??

...
    private const uint URL_COUNT = 18;
    private string[] _urls;

    public Redirector()
    {
        this._urls = new string[URL_COUNT];
        ...
    }
...

Results in “A constant value is expected “ and underlines URL_COUNT in the array definition??

Whats URL_COUNT if it isn’t a const -ant value?!?!

EDIT Phew, i thought for a second then i was going mad. I'm glad no one could repro this as that means it's just a local thing. Thanks for your help guys.

Upvotes: 2

Views: 3515

Answers (3)

Razzie
Razzie

Reputation: 31222

This will only fail to compile when you supply both the dimension lengths and an array initializer. For example:

this._urls = new string[URL_COUNT];

will be fine, but:

this._urls = new string[URL_COUNT] { "One", "Two" };

will not. The latter requires a constant expression. Note that a const variable is not a constant expression, just a constant value. From the C# specification (3.0) par 12.6:

When an array creation expression includes both explicit dimension lengths and an array initializer, the lengths must be constant expressions and the number of elements at each nesting level must match the corresponding dimension length.

Upvotes: 10

sisve
sisve

Reputation: 19781

This works too, without any complaints from the compiler.

class Foo {
    private const uint URL_COUNT = 18;
    private readonly string[] _urls = new string[URL_COUNT];
}

Upvotes: 2

Andrew Hare
Andrew Hare

Reputation: 351476

It is a constant and should work fine. The following code compiled fine for me with the C# 3 compiler:

using System;

class Foo
{
    private const uint URL_COUNT = 18;
    private string[] _urls;

    public Foo()
    {
        this._urls = new string[URL_COUNT];
    }
}

Upvotes: 5

Related Questions