shinzou
shinzou

Reputation: 6192

Set and get properties and constants differences

Is there any difference between the following declarations (other than the difference between the const and static readonly)?

public static int foo1 { get; } = 8;

private static readonly int foo2 = 4;
public static int Foo2
{
    get { return foo2; }
}

private const int foo3 = 9;
public static int Foo3
{
    get { return foo3;}
}

What happens behind the scenes with foo1? is it the same as foo2 or foo3?

I ask about foo1 because I can't make it a const or readonly with this syntax, so I also ask if it's actually a constant?

Upvotes: 2

Views: 79

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500675

It's the same as foo2. The difference with foo3 is that the property access won't even consult foo3 - Foo3 is compiled to code equivalent to

public static int Foo3
{
    { get { return 9; } }
}

Now admittedly from the perspective of calling code it really doesn't matter - in all cases you're exposing a property which will always return the same value.

If you want the equivalent of Foo3 without the const, you could use:

public static int Foo4 => 10;

Upvotes: 4

Related Questions