Tuple (C#)

Definition: tuples are data structures with multiple fields (light construct) for lightweight data transport mechanism.

Initialization:

// ("a", true, 4, "t");
// (string, bool, int, string) values=("a", true, 4, "t");

var values=("a", true, 4, "t");

// named fields
// (string FirstName, string MiddleName, string LastName) names=("Jack", "Von", "Chole");

var names=(FirstName: "Jack", MiddleName: "Von", LastName: "Chole");

// access tuple values
Console.WriteLine($"First Name: {names.FirstName}); // by field name
// Console.WriteLine($"Last Name: {names.Item3}); // through ItemX

Tuple equality(==) and inequality(!=)

var tuple1=(x: 10, y: 20);
(int? x, int? y) tuple2=(10, 20);
Console.WriteLine(tuple1==tuple2); // true

(long a, int b) first=(10, 20);
(int a, long b) second=(10, 20);
Console.WriteLine(first==second); // true

Tuple as Method return value

static (string firstName, string lastName, int age) GetPersonInfo()
{
    return( "Jack", "Chen", 25);
}

var p=GetPersonInfo();
Console.WriteLine($"{p.firstName} {p.lastName} is {p.age} years old.")

Tuple Pattern Matching (switch)

static string ColorMixer(string color1, string color2)
{
    //return (color1, color2) switch
    =>(color1, color2) switch
    {
        ("red", "green")=>"yellow",
        ("green", "blue")=>"cyan",
        ("red", "blue")=>"magenta",
        (_, _)=>"unknown",
    };
}

Deconstruct Tuples with Positional Pattern Matching (C# 8.0) 

namespace FunWithTuplePatternMatch
{
    public static class Common
    {
        public static string GetQuadrant(Point p)
        {
            var value = (p.Deconstruct());
            return value  switch
            {
                var (x, y) when x==0 && y==0 => "Origin",
                var (x, y) when x > 0 && y > 0 => "First",
                var (x, y) when x < 0 && y > 0 => "Second",
                var (_, _) => "unknown",
            };
        }

        public struct Point
        {
            // fields
            public double X;
            public double Y;

            // custom constructor
            public Point(double xValue, double yValue)
            {
                X = xValue;
                Y = yValue;
            }

            // deconstruct Tuple
            public (double xValue, double yValue) Deconstruct() => (X, Y);
        }
    }
}
using static FunWithTuplePatternMatch.Common;

Point p = new Point(10, 20);
var pV = p.Deconstruct();
Console.WriteLine($"X is {pV.xValue}");
Console.WriteLine($" Y is {pV.yValue}");
Console.WriteLine($"The quadrant is {GetQuadrant(p)}");

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值