Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Public constants in WinRT Component Library

I have created a C# Windows Runtime component, and the following line:

public const bool LOG_ENABLED = false;

is throwing an error:

Type 'Constants' contains externally visible constant field 'Constants.LOG_ENABLED'. Constants can only appear on Windows Runtime enumerations

What does this error mean? And how can I declare constants?

like image 426
csaam Avatar asked Dec 12 '12 21:12

csaam


Video Answer


1 Answers

This is an old question, but Ill give my two cents non the less. const and public is a dangerous combination and often miss used. This is due to the fact that if a public const field is changed in a library the library cannot just be replaced but rather all the clients of that library needs to be rebuilt since it would have copied the actual value in the client and not the reference to that value.

One option is to do something like this if you really wanted a public "constant":

public static class Constants
{   
    public static readonly bool LOG_ENABLED = false;
}

However this also fails in the WinRT component library

'WindowsRuntimeComponent1.Constants' contains externally visible field 'System.Boolean WindowsRuntimeComponent1.Constants.LOG_ENABLED'. Fields can be exposed only by structures.

Another alternative that does indeed work is

public static class Constants
{
    public static bool LOG_ENABLED { get { return false; } }
}

I am not exactly sure why it is not possible to have a public const or readonly in a WinRT component library since it is possible in a normal class library.

After some reading it seems like public fields are limited to structs and structs may ONLY contain public fields.

Like you said in the comments, changing it to internal was a good option if you do not use it from an external source.

like image 91
Murdock Avatar answered Sep 29 '22 02:09

Murdock