DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations

C# Tuples: New C# 7 Language Feature

A tuple is a mathematical concept that is just a list of elements. Take a look at the basics of how tuples work in C# 7 and see C# tuples in action with Couchbase.

Matthew Groves user avatar by
Matthew Groves
·
May. 04, 17 · Opinion
Like (3)
Save
Tweet
Share
3.69K Views

Join the DZone community and get the full member experience.

Join For Free

c# tuples are a new feature of c# 7. i’m going to show you the basics of how c# tuples work. i’m also going to mix in a little couchbase to show tuples in action. however, if you don’t want to install couchbase just to play around with tuples, don’t worry — you will still be able to follow along.

the source code that i use for this blog post is available on github for you to try out if you’d like.

note: if you’ve been using c# for a while, you might remember the tuple class that was introduced in .net 4 . that class still exists, but it is not the same thing as the new tuple feature of c#.

what are c# tuples?

a “tuple” is a name for a mathematical concept that is just a list of elements. in the lisp family of languages, coding is built almost entirely around the idea that everything is a list. c# once again borrows the kernel of an idea from the functional programming world and integrates it into a non-functional language. so, we get c# tuples (check out the original c# tuple proposal by mads torgersen for more details and background).

remember anonymous types?

but to make it simple, let’s consider something you may already be familiar with in c#, an anonymous type. to review, you can instantiate a new object without specifying a type:

var myobject = new { foo = "bar", baz = 123 };

behind the scenes, there actually is a type that inherits from the base object type, but generally speaking, we only deal with the object, not its type.

additionally, i can’t return an anonymous type from a method or pass an anonymous type as a parameter without losing the type information in the process.

private object getanonymousobject()
{
    return new {foo = "bar", baz = 123};
}

private void anothermethod()
{
    var obj = getanonymousobject();
    console.writeline(obj.foo); // compiler error :(
}

they are useful, certainly, but i generally refer to these as anonymous objects as i use them, for these reasons.

what’s this got to do with c# tuples?

i think of c# tuples as richer anonymous types. they are a way to create a “class” on the fly without actually defining a class. the syntax for tuples is to simply put parenthesis around a comma separated list of types and names. a tuple literal is just a comma separated list of literals also surrounded by parenthesis. for instance:

(string firstname, string lastname) mytuple = ("matt", "groves");

console.writeline(mytuple.firstname); // no compiler error :)
console.writeline(mytuple.lastname);  // no compiler error :)

note: right now, i’m preferring pascalcase for tuple properties. i don’t know if that’s the official guideline or not, but it “feels” right to me.

c# tuples in action

i put tuples to work in a simple console app that interacts with couchbase.

i created a buckethelper class that is a very simple facade over the normal couchbase ibucket . this class has two methods: one to get a document by key and return a tuple and one to insert a tuple as a document.

public class buckethelper
{
    private readonly ibucket _bucket;

    public buckethelper(ibucket bucket)
    {
        _bucket = bucket;
    }

    public (string key, t obj) gettuple<t>(string key)
    {
        var doc = _bucket.get<t>(key);
        return (doc.id, doc.value);
    }

    public void inserttuple<t>((string key, t obj) tuple)
    {
        _bucket.insert(new document<t>
        {
            id = tuple.key,
            content = tuple.obj
        });
    }
}

to instantiate this helper, you just need to pass an ibucket into the constructor.

tuple as a return type

you can then use the gettuple method to get a document out of couchbase as a tuple.

var buckethelper = new buckethelper(bucket);

(string key, film film) fightclub = buckethelper.gettuple<film>("film-001");

the tuple will consist of a string (the document key) and an object of whatever type you specify. the document content is json and will be serialized to a c# object by the .net sdk.

also, notice that the name of the tuple properties don’t have to match. i used obj in buckethelper but i used film when i called gettuple<film> . the types do have to match, of course.

tuple as a parameter type

i can also go the other way and pass a tuple as a parameter to inserttuple .

string key = guid.newguid().tostring();
film randomfilm = generaterandomfilm();
buckethelper.inserttuple((key, randomfilm));

the generaterandomfilm method returns a film object with some random-ish values (check out the github source for details). a tuple of (string, film) is passed to inserttuple . the couchbase .net sdk takes it from there and inserts a document with the appropriate key/value.

running the console app, you should get an output that looks something like this:

note that the couchbase .net sdk at this time doesn’t have any direct tuple support, and it may not ever need it. this code is simply to help demonstrate c# tuples. i would not recommend using the buckethelper as-is in production.

tuh-ple or too-ple?

i seem to remember my professor(s) pronouncing it as “too-ple,” so that’s what i use. like the hard-g/soft-g debate of “gif,” i’m sure there are those who think this debate is of the utmost importance and are convinced their pronunciation is the one true way. but, both are acceptable .

Tuple

Published at DZone with permission of Matthew Groves, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Software Maintenance Models
  • What’s New in the Latest Version of Angular V15?
  • High-Performance Analytics for the Data Lakehouse
  • Top 11 Git Commands That Every Developer Should Know

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: