1

I have the following code:

object foo = ("hello", "world");
var bar = foo as (string, string)?;
if (bar != null) { Console.WriteLine(bar.Value.Item1); }

Edit: I should say that foo is just an example of a variable I might receive in object form but should be able to convert.

Resharper highlights the 'as (string, string)' and suggests I Use Pattern Matching and when I accept, this is the result:

object foo = ("hello", "world");
if (foo is (string, string) bar) { Console.WriteLine(bar.Item1); }

This looks like it should be ok but it does not compile as (string, string) is highlighted with the error No 'Deconstruct' method with 2 out parameters found for type 'object'

While this code transformation seems like a resharper bug, this is not strictly a resharper-specific question as I'd like to know how should I write this? My original code worked fine but is there a way I can do what my original code is doing with pattern matching?

randonoob
  • 65
  • 5
  • Because `object` does not have a `Deconstruct()` method. Any particular reason why you use `object foo =` instead of `var foo = `? – Mushroomator Aug 10 '23 at 17:38
  • In my program I'd be receiving an `object` that I'd be attempting to cast to `(string, string)` and I just did I `object foo = ("hello", "world")` as an example of such an object I might be passed – randonoob Aug 10 '23 at 17:40
  • 2
    Related or duplicate: [Using `is` operator with value type tuples gives error](https://stackoverflow.com/q/56103160). [How to use C# pattern matching with tuples](https://stackoverflow.com/q/63582128) also seems related. Do either of those answer your question? Also, are you using **C# 7** or **.NET 7**? .NET 7 [corresponds to C# 11](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/configure-language-version). – dbc Aug 10 '23 at 17:51
  • Both syntaxes from [this answer](https://stackoverflow.com/a/56103294/3744182) by canton7 to [Using `is` operator with value type tuples gives error](https://stackoverflow.com/q/56103160/3744182) work with your `foo` object, see https://dotnetfiddle.net/zYIpMf. Looks like a duplicate. – dbc Aug 10 '23 at 17:57
  • The first one did help as I think I'll just have to use `ValueTuple` instead of `(string, string)`. – randonoob Aug 10 '23 at 17:57
  • Filed a bug for R# - https://youtrack.jetbrains.com/issue/RSRP-493832/ – Igor Akhmetov Aug 19 '23 at 11:16

1 Answers1

2

Unfortunately resharper made your code erroneous.

var bar = foo as (string, string)?; // foo casts to tuple
...
if (foo is (string, string) bar) // there is no cast, foo is still object
var foo = ("hello", "world"); // can be a solution here, object causes the error after refactoring
rotabor
  • 561
  • 2
  • 10
  • Sorry I updated my original post to say that `foo` is just an example of a variable I might receive in object form but should be able to convert. – randonoob Aug 10 '23 at 17:49