2

Suppose there is such a record

public record ExampleRecord(int a, int b);

and a method

public int ExampleMethod((int a, int b) t)
{
    return t.a + t.b;
}

Is it possible to do something like this to work with record as tuple parameter?

var t = new ExampleRecord(a: 1, b: 2);
ExampleMethod(t);
KyleMit
  • 30,350
  • 66
  • 462
  • 664
Jiruffe
  • 47
  • 5
  • No, I'm afraid there isn't. Whilst records can be deconstructed, that's not the same as turning them into a tuple - instead it's using tuple syntax to deconstruct a record into a number of disparate variables. – Yair Halberstadt Feb 22 '21 at 06:40
  • Its questionable why you would want to do this. either use a `ValueTuple`, be nice to your allocations and take the copy hit. Or use an immutable record, take the allocation, and pass by reference. Doing both is like running away from the circus to join the orphanage – TheGeneral Feb 22 '21 at 06:50

2 Answers2

6

You can add an implicit conversion to your record type:

public record ExampleRecord(int a, int b)
{
    public static implicit operator ValueTuple<int, int> (ExampleRecord record)
    {
        return (record.a, record.b);
    }
}

Use like this:

var t = new ExampleRecord(a: 1, b: 2);
ExampleMethod(t);

You can make extension methods. For example:

public static class ExampleRecordExtensions
{
    public static (int, int) ToTuple(this ExampleRecord record)
    {
        return (record.a, record.b);
    }
}

Use like this:

var t = new ExampleRecord(a: 1, b: 2);
ExampleMethod(t.ToTuple());

Alternatively you can use deconstruction. Use like this:

var t = new ExampleRecord(a: 1, b: 2);
ExampleMethod((_, _) = t);

I remind you that record types are classes. These tuples are value types (ValueTuple). Which also means that the tuple you create form the record type will always be a copy of the data.

Theraot
  • 31,890
  • 5
  • 57
  • 86
  • Nice answer - my favorite is to use the extension method strategy because it's much clearer what's going on – KyleMit Nov 23 '22 at 19:20
0

The record type automatically generates a deconstructor method for converting the record values into ValueTuple type. Please refer https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/record#positional-syntax-for-property-definition

You can use like this, with your ExampleRecord:

var (a, b) = new ExampleRecord(a: 1, b: 2);
ExampleMethod((a, b));
int ExampleMethod((int a, int b) t)
{
    Console.WriteLine($"a: {a}, b:{b}"); //output a: 1, b:2
    return t.a + t.b;
}
Elangovan Manickam
  • 413
  • 1
  • 5
  • 14