Where's Deconstruct method of KeyValuePair<> struct?
Asked Answered
H

3

7

I'm sure that previously I saw this method, because one year ago I've asked: What is the purpose of Deconstruct method in KeyValuePair<> struct?

But now I simply can't find it, or any trace about it's removal, any questions, nothing.

Compiler agrees:

var s = new KeyValuePair<int, int>(1, 3);
var (x, y) = s;

Error CS1061 'KeyValuePair' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'KeyValuePair' could be found (are you missing a using directive or an assembly reference?

Error CS8129 No suitable 'Deconstruct' instance or extension method was found for type 'KeyValuePair', with 2 out parameters and a void return type.

What's going on?

Helaina answered 15/7, 2019 at 21:4 Comment(0)
H
11

You might be running your code on .NET Framework. Whilst the C# 7 deconstruction syntax is supported in both .NET Framework and .NET Core, the Deconstruct method for KeyValuePair<TKey,TValue> is currently only supported in .NET Core 2.0 and later. You can check the "Applies to" section on Microsoft Docs.

Haff answered 15/7, 2019 at 21:13 Comment(0)
H
6

Oops. Looks like it was not added everywhere initially:

As documentation says:

Applies to

.NET Core

  • 3.0 Preview 6
  • 2.2
  • 2.1
  • 2.0

.NET Standard

  • 2.1 Preview

Looks like I was targeting .NET Core one year ago, and now I'm on .NET Standard 2.0.

Helaina answered 15/7, 2019 at 21:14 Comment(0)
S
4

I encountered this with .net standard 2.0 (which is required when creating Source Generators). This can be easily added with:

public static class KeyValuePairExtensions {
    public static void Deconstruct<TKey,TValue>( this KeyValuePair<TKey, TValue> keyValuePair, out TKey key, out TValue value ) {
        key   = keyValuePair.Key;
        value = keyValuePair.Value;
    }
}
Stiffen answered 27/1, 2023 at 12:15 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.