Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# 7.0 case pattern matching on generic parameter

Is there a reason for not being able to handle a generic variable by the type pattern? Please consider the code:

public static int CompareValues<T>(T left, T right)
{
  switch (left)
  {
    case IComparable<T> comparableDif:
      return comparableDif.CompareTo(right);
    case System.Numerics.Complex c:
      return c.Magnitude
        .CompareTo(((System.Numerics.Complex)(object)right).Magnitude);
    default:
      throw new ArgumentException("unsupported type");
  }
}

The first match on the IComparable interface is ok, but the second one does not compile. Why do I have to use this boxing workaround?

case object o when o is System.Numerics.Complex:
  return ((System.Numerics.Complex)o).Magnitude
    .CompareTo(((System.Numerics.Complex)(object)right).Magnitude);
like image 479
neonxc Avatar asked Jun 25 '17 08:06

neonxc


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr. Stroustroupe.

Is C language easy?

C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.

How old is the letter C?

The letter c was applied by French orthographists in the 12th century to represent the sound ts in English, and this sound developed into the simpler sibilant s.


1 Answers

This is a consequence of how pattern matching in C# 7.0 is defined: for your type pattern to compile, a cast from T to Complex would have to exist, but it does not. The C# team realized it was a mistake to require this, so this issue was fixed in C# 7.1.

like image 134
svick Avatar answered Sep 27 '22 19:09

svick