12
submitted 3 years ago* (last edited 3 years ago) by jim_stark@programming.dev to c/dotnet@programming.dev

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

you are viewing a single comment's thread
view the rest of the comments
[-] ex0dus@lemmy.sdf.org 1 points 3 years ago* (last edited 3 years 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".

this post was submitted on 04 Jul 2023
12 points (100.0% liked)

.NET

1869 readers
1 users here now

Getting started

Useful resources

IDEs and code editors

Tools

Rules

Related communities

Wikipedia pages

founded 3 years ago
MODERATORS