Enum not existing in context, but it is right there!

I come from a C/C++ background and am picking up on C#, but I’m getting an error in C# that I don’t readily understand. Is it a problem with C#, Unity3D, or my understanding of C#?

In the following code where I assign to “aVariable”, I get the error that “The name ‘ENUM1’ does not exist in the current context”. However, if I just add the qualifier “TestEnum.” to it, it works. Examples of C# on the web and Unity forums using enums do not show this qualifier as necessary and it isn’t necessary in C/C++, so the error caught me by surprise.

using UnityEngine;
using System.Collections;

public class Test : MonoBehaviour {
	enum TestEnum { ENUM1 };
	TestEnum aVariable;

	// Use this for initialization
	void Start () {
		aVariable = ENUM1;  // The error occurs here. "ENUM1" is not available in this context.
	}
}

2 Answers

2

This is a key difference between C/C++ and C#: in C# the enum must be used like so:

TestEnum aVariable = TestEnum.ENUM1;

so as to avoid confusion if the same name exists in multiple enums. You can only use the name on its own if you are still within the context of the enum declaration:

enum TestEnum {
    Value1 = 1,
    Value2 = Value1 + 5
}

Write using static Test.TestEnum; at the top of the script and make TestEnum public.