0

Is it possible in C# to define a variable like so?

switch(var num = getSomeNum()) {
   case 1: //Do something with num
           break;

   default: break;
}

public static int GetSomeNum() => 3;
  • Well, what does the compiler tell you? – Peter Bons Jun 15 '17 at 07:59
  • 1
    Somehow your question is similar to this https://stackoverflow.com/questions/8155772/setting-a-variable-to-a-switchs-result – Salah Akbari Jun 15 '17 at 08:00
  • Possible duplicate of [Setting a Variable to a Switch's Result](https://stackoverflow.com/questions/8155772/setting-a-variable-to-a-switchs-result) – Tetsuya Yamamoto Jun 15 '17 at 08:06
  • The answer is no. – Matthew Watson Jun 15 '17 at 08:06
  • I saw you deleted your question on xamarinstudio.xunit. I think you happened to hit a bug (single test case is not properly handled), which I just fixed in a new release, https://github.com/xunit/xamarinstudio.xunit/releases/tag/v0.7.6 You can download the .mpack and manually install it following the readme file, https://github.com/xunit/xamarinstudio.xunit/ – Lex Li Jun 16 '17 at 18:57
  • @LexLi hey, I haven't deleted it, I was redirected to a different sub-forum and the issue was resolved there, and the thread closed. Thank you, indeed installing the new release fixed the problem! :) –  Jun 26 '17 at 13:26

1 Answers1

2

The documentation says that

In C# 6, the match expression must be an expression that returns a value of the following types:

  • a char.

  • a string.

  • a bool.

  • an integral value, such as an int or a long.

  • an enum value.

Starting with C# 7, the match expression can be any non-null expression.

To answer your question,

Yes you can switch on an int, e.g.

int myInt = 3;
switch(myInt)

Yes you can switch on the result of a method that returns an it, e.g.

int GetMyInt() 
{
    // Get my Int
}

switch(GetMyInt())

Yes you can switch on variable populated with a method result, e.g.

int GetMyInt() 
{
    // Get my Int
}

int myInt = GetMyInt();

switch(myInt)

No you can't do it like that.

Gareth
  • 913
  • 6
  • 14
  • Thanks! I was asking because I saw the microsoft keynote about c# 7 but haven't remembered correctly all the new stuff they introduced and couldn't find anywhere an answer. –  Jun 15 '17 at 08:17