Jack
Jack

Reputation: 7557

Optional Argument: compile time constant issue

Why is this working:

public int DoesEmailAddressExistsExcludingEmailAddressID(
    string emailAddress, 
    string invitationCode, 
    int emailAddressID = 0, 
    int For = (int) Enums.FOR.AC)

whereas this doesn't

public int DoesEmailAddressExistsExcludingEmailAddressID(
    string emailAddress, 
    string invitationCode, 
    int emailAddressID = 0, 
    int For = Enums.FOR.AC.GetHashCode())

where AC is enum. Can enums's hashcode change at runtime?

Upvotes: 1

Views: 126

Answers (2)

Matthias Meid
Matthias Meid

Reputation: 12523

There is a good chance that an Enum's hash code remains constant during a program's runtime. However, this is not guaranteed at compile time. Therefore it cannot be a compile-time constant.

Moreover, as Daniel already mentioned, GetHashCode has to be executed to determine the value, which can obviously not be done at compile-time.

Upvotes: 2

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174329

GetHashCode is a method. The return value of a method is not a compile time constant as code needs to be executed to determine the return value.
It doesn't matter whether or not the method returns always the same.

Upvotes: 5

Related Questions