Trying to tidy up scope and avoid possible multiple calls to RegisterWindowMessage.
Currently have a class used once with the following member
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
static extern int RegisterWindowMessage(string lpString);
private int m_message = RegisterWindowMessage("MY_MSG");
As we only have one instance this seems ok, but think it would be more tidy to use. With my basic C# understanding this should call RegisterWindowMessage and assign the result to int and not allow it to change.
private const int message = RegisterWindowMessage("MY_MSG");
however attempting to do so leads to a
error CS0133: The expression being assigned to 'someclass.messageEvent' must be constant
so now I’m confused, does this mean the function was being assigned and called each time m_message was used previously, is there something else missing?
A
constfield has to be a compile-time constant. If you just want something which won’t change at execution time after initial assignment1, make it readonly:Note that I’ve made this static, which
constis implicitly. This meansRegisterWindowMessagewill only be called once for this AppDomain, which is what I think you want.EDIT: Hans is right, you should check the return value. You could either do that when you first use it, or when the type is initialized – usually it’s a bad idea for type initializers to throw exceptions, but you should see what the impact is.
1 Strictly speaking, a static readonly field can be assigned in the declaration or in the static constructor; an instance readonly field can be assigned in the declaration or in any instance constructor. It can be assigned multiple times, which is usually not useful, but can be just occasionally.