Owen Johnson
Owen Johnson

Reputation: 2516

Is it possible to check compiler constants at runtime in C#?

I know I can conditionally set variables by conditionally including code like so:

#if DEBUG
   someVar = "foo";
#else
   someVar = "bar";
#endif

I would rather enumerate or test for compiler constants at runtime.

For example, I want to put all of the symbols defined at compile time in a window title so that testers can see which build they are testing.

Upvotes: 4

Views: 1768

Answers (3)

Owen Johnson
Owen Johnson

Reputation: 2516

The compiler constants aren't stored anywhere in the compiled assembly. Because of this, there is no way to access them at runtime.

Upvotes: 1

Ryan
Ryan

Reputation: 6517

I think the preprocessor removes the unused code at compilation time.

But you can accomplish the same thing in a cleaner way using conditional attributes:

[Conditional("DEBUG")]
public void DrawDebugTitle() {
   Form1.Title = "Debug mode";
}

Then simply call the method normally, and if DEBUG is defined then it will change the form's title, and if DEBUG isn't defined then the method call, while still appearing in your code, will do nothing.

Upvotes: 4

konkked
konkked

Reputation: 3231

I don't think you can dynamically enumerate them

The only things you can do with compiler constants in C# is define them and undefine them with def,undef and see if they exist withif,else,elif,endif, once the program has been compiled there is no way to tell what variables you have unless you do something like this

private static List<string> compileConstants = new List<string>();

#if DEBUG
  compileConstants.Add("DEBUG");
#endif

Besides that I don't think there is any other way. Compiler Constants are defined and used when the information is being passed to assembly I don't think it is actually persisted in a way that you can access them during run time in C#

Upvotes: 4

Related Questions