Anthony Bias
Anthony Bias

Reputation: 646

Using a Form Handle for a Case in a Switch Statement?

I've been racking my brain trying to figure out how to write this VB code

 Case frm.hwnd:

in C# so that it will work in a switch statement using a long as a test expression. When I try

case (long)frm.Handle:

my IDE tells me that I need to use a constant expression. I've tried both casting the form handle into a long and assigning it to a constant long variable

const long frmHandle = new (long)frm.Handle;

and instantiating an IntPtr object to cast into a long when I use it as a case expression.

const IntPtr frmHandle = new IntPtr(frm.Handle);

The former caused an error saying

the value being assigned must be constant

and the latter caused an error saying

IntPtr cannot be declared as constant

Is there any way to still use the form handle as a case?

Upvotes: 0

Views: 258

Answers (2)

Coder95
Coder95

Reputation: 73

I think you have to use an "if" for this:

if(variable == frm.Handle)

A switch case is just an better looking if else ;-)

Upvotes: 0

Eric J.
Eric J.

Reputation: 150108

The switch statement is used with (compile-time) constant expressions, not variables. You cannot use a window handle with one.

const IntPtr frmHandle = new IntPtr(frm.Handle);

frmHandle is not a compile time constant. This syntax states that it cannot be changed after it is initialized.

You can achieve the same thing, but with a variable, with a series of if statements. Depending on your real needs, you might also use a dictionary using the window handle as a key (the value would depend on what you're trying to achieve here).

Upvotes: 2

Related Questions