The documentation uses is in the example for “declaration patterns” but the book I am reading uses a switch statement. But when I try to run the code I run into errors.

using System;

public class Program
{
  public static void Main()
  {
    var o = 42;

    switch (o) {
      case string s:
        Console.WriteLine($"A piece of string is {s.Length} long");
        break;

      case int i:
        Console.WriteLine($"That's numberwang! {i}");
        break;
    }
  }
}

Error:

Compilation error (line 7, col 6): An expression of type 'int' cannot be handled by a pattern of type 'string'.

EDIT

Changing from

var o = 42;

to

object o = 42;

worked.

Full code: https://github.com/idg10/prog-cs-10-examples/blob/main/Ch02/BasicCoding/BasicCoding/Patterns.cs

  • ex0dus@lemmy.sdf.org
    link
    fedilink
    arrow-up
    3
    ·
    edit-2
    1 year ago

    Your code does not follow the pattern matching syntax; I don’t see “is” anywhere. That’s what is actually doing the casting

    Edit: I think I’m completely wrong about “is” being required

    • jim_stark@programming.devOP
      link
      fedilink
      arrow-up
      2
      ·
      1 year ago

      I see.

      The book uses a very specific scenario where o is an object that would accept any type. So using the object data type worked. Check the OP for the edit.

      • ex0dus@lemmy.sdf.org
        link
        fedilink
        arrow-up
        1
        ·
        1 year ago

        I see, using “is” could be a downcast from any type. But from object it would always be an upcast so you don’t need an explicit casting operator

  • Lmaydev@programming.dev
    link
    fedilink
    arrow-up
    2
    ·
    edit-2
    1 year ago

    An integer will never be a string. Originally you create an integer variable so it’s telling you the string case is pointless.

  • RubberDucky@programming.dev
    link
    fedilink
    arrow-up
    2
    ·
    edit-2
    1 year ago

    So c# in runtime already knows the type of o(unless you do some silly magic ofcourse) If you wanna change o for debug purposes you can try .GetType() and typeOf

    You can check the type with

    bool isString = o.GetType() == typeof(string);
    

    (Sorry for any errors I’m on phone so code fiddlers aren’t that great)

    • jim_stark@programming.devOP
      link
      fedilink
      arrow-up
      1
      ·
      1 year ago

      The book uses a very specific scenario where o is an object that would accept any type. So using the object data type worked. Check the OP for the edit.

  • ex0dus@lemmy.sdf.org
    link
    fedilink
    arrow-up
    1
    ·
    edit-2
    1 year ago

    The “is” is a part of pattern matching which I don’t believe regular switches can do. Only switch expressions. The example in the link you gave is checking the type by casting using “is”.