C# Tuples (Think Python)

Recently I took a few courses with Udacity to brush up on my coding skills and to learn the Python programming language which has been a goal of mine for a while. I found myself really liking Python and its style of doing things. One of my favorite parts was the ability to return a tuple, or basically any number of variables, from a function. This eliminates the need for ref parameters or other workarounds.

While writing a tool in C# recently, I found myself wanting to return a tuple like in Python. Unfortunately I had no knowledge of how to do this and didn’t think it could be done. I did a quick search to amuse myself and what do you know, I found this. It turns out that .NET added a Tuple class after all! It’s not quite as clean because it’s templated but hey, the functionality is there.

public Tuple<Version, string> GetVersion()
    Version version;
    string download_url;

    // Code to download and parse version info/download URL
    return new Tuple<Version, string>(version, download_url);

public void DoUpdate()
    Tuple<Version, string> version_info = GetVersion();
    Console.WriteLine(version_info.Item1.ToString();  // Print the version number
    Console.WriteLine(version_info.Item2);  // Print the download URL

And there you have it. Let me know if you have any other neat tricks between C# and Python!


This entry was posted in Programming and tagged , . Bookmark the permalink.

2 Responses to C# Tuples (Think Python)

  1. cyberneurology says:

    Can Tuples have more than two variables or is a Tuple a tuple in the pre-Python sense?

    • Laptop765 says:

      It looks like the Tuple class is templated for up to 8 variables. So it’s not truly as dynamic as Python’s. However, it’s good enough for most cases.

Leave a Reply

Your email address will not be published. Required fields are marked *