1

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?

3
  • 2
    GetHashCode() requires executing code. Which means it is not a compile time constant. Commented Sep 4, 2012 at 14:58
  • The solution for this problem, by the way, is to use the classic C# overloading approach, rather than using default arguments. Commented Sep 4, 2012 at 15:15
  • I strongly suggest not using For as a variable name. The first example as is would not actually compile. Commented Sep 4, 2012 at 15:34

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

1 Comment

+1 for a good point: in practice we know that it's virtually certain that an enum's hash code will always be the same, but it's not guaranteed, so the compiler has to treat the method call like any other.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.