What are the properties of a tuple called?

How the return from a method that returns the type of a tuple with the name of the parameters is organized, as an example

private static Tuple<string, string> methodTuple()
{
    return new {Name = "Nick", Age = "Twenty"}; /*exception because need to new Tuple<string, string>(){Item1 = "Nick", Item2 = "Twenty"}o*/
}

      

and call parameters like methodTuple.Name

, and notmethodTuple.Item1....N

Is it possible or not?

UPD: I want to create an object with named parameters without a new named type.

+11


source to share


8 answers


To do this, you need to declare a helper class.

public class MyResult
{
    public string Nick { get; set; }
    public string Age { get; set; }
}

      

What you are trying to return is an anonymous type. As the name suggests, you don't know what it is called, so you cannot declare your method to return it.

Anonymous Types (C # Programming Guide)

You cannot declare a field, property, event, or return type. method as having an anonymous type. Similarly, you cannot declare a formal parameter of a method, property, constructor, or indexer as having an anonymous type. To pass an anonymous type or a collection that contains anonymous types, you can declare the parameter as an object type as an argument to a method. However, this defeats the purpose of strong typing. If you must store query results or pass them outside of method boundaries, consider using a regular named structure or class instead of an anonymous type.



Update

C # 7 introduces native language support for Tuple and comes with named tuples

(string name, int age) methodTuple()
{
    (...)
}

      

Find out more at docs.microsoft.com: https://docs.microsoft.com/en-us/dotnet/articles/csharp/csharp-7#tuples

+13


source


There is a new option in C # 7.0 (Visual Studio 2017):



(string first, string middle, string last) LookupName(long id)

      

+11


source


This is not possible with Tuple

, no. To do this, you need to create your own new type.

+6


source


Starting with C # v7.0, it is now possible to assign the names of tuple properties that were previously used by default to names such as Item1

, Item2

and so on.

By naming the properties of Tuple Literals :

var myDetails = (MyName: "RBT_Yoga", MyAge: 22, MyFavoriteFood: "Dosa");
Console.WriteLine($"Name - {myDetails.MyName}, Age - {myDetails.MyAge}, Passion - {myDetails.MyFavoriteFood}");

      

Console output:

Name - RBT_Yoga, Age - 22, Passion - Dosa

Returning a tuple (with named properties) from a method :

static void Main(string[] args)
{
    var empInfo = GetEmpInfo();
    Console.WriteLine($"Employee Details: {empInfo.firstName}, {empInfo.lastName}, {empInfo.computerName}, {empInfo.Salary}");
}

static (string firstName, string lastName, string computerName, int Salary) GetEmpInfo()
{
    //This is hardcoded just for the demonstration. Ideally this data might be coming from some DB or web service call
    return ("Rasik", "Bihari", "Rasik-PC", 1000);
}

      

Console output:

Employee data: Rasik, Bihari, Rasik-PK, 1000

Creating a list of tuples with named properties

var tupleList = new List<(int Index, string Name)>
{
    (1, "cow"),
    (5, "chickens"),
    (1, "airplane")
};

foreach (var tuple in tupleList)
    Console.WriteLine($"{tuple.Index} - {tuple.Name}");

      

Console output:

1 - cow 5 - chickens 1 - plane

I hope I have covered everything. In case there is something I missed, please give me feedback in the comments.

Note . My code snippets use the C # v6 string interpolation feature as detailed here .

+5


source


I usually create a new type derived from Tuple and map your explicit properties to return the properties of the base ItemX class. eg:

public class Person : Tuple<string, string>
{
    public Key(string name, string age) : base(name, age) { }

    public string Name => Item1;
    public string Age => Item2;
}

      

+1


source


Unfortunately, this is not possible with the "Tuple" type as it is defined as "Item1 ... N" on MSDN. Thus, this exception is valid.

This method can be compiled in three ways: 1.) Change the return type to an object - this will create an "anonymous" type that you can then use later. This is not particularly useful if you want to access the Name or Age property later without additional work. 2.) Change the return type to dynamic - this will allow you to access the "Name" and "Age" properties, but will make the whole program (only the DLL where this method is actually located) a little slower, since using dynamic requires throwing -for strong typing. 3.) Create a class and use it as a return type.

Sample code here:

private static object ObjectTuple()
        {
            return new { Name = "Nick", Age = "Twenty" };
        }

        private static dynamic DynamicTuple()
        {
            return new { Name = "Nick", Age = "Twenty" };
        }

        private static Temp TempTuple()
        {
            return new Temp{ Name = "Nick", Age = "Twenty" };
        }

        class Temp
        {
            public string Name { get; set; }
            public string Age { get; set; }
        }

      

0


source


As me, when you want to return or get a lot of things from one method, it is better to make it the return type as CLASS, but if you are going to use Tuple, which is itself a class, then for better naming this new class should inherit from Tuple, such as those mentioned below ...

 public CustomReturn ExecuteTask( int a, string b, bool c, object d )
        {
        // Calling constructor of CustomReturn Class to set and get values
          return new CustomReturn(a,b,c,d);
        }

        internal class CustomReturn 
        // for tuple inherit from Tuple<int,string,bool,object,double>
        { 
          //for tuple public int A{ get {this.Item1} private set;}

          public int A{get;private set;}
          public string B{get;private set;}
          public bool C{get;private set;}
          public object D{get;private set;}

          public CustomReturn (int a, string b, bool c, object d )
              // use this line for tuple ": base( obj, boolean )"
            {
              this.A = a;
              this.B = b;
              this.C = c;
              this.D = d;
            }

        }

    Main(args)
    {
      var result = ExecuteTask( 10, "s", true, "object" );
      // now if u have inherited Tuple for CustomReturn class then 

      // on doing result. you will get your custom name as A,B,C,D for //Item1,Item2,Item3,Item4 respectively also these Item1,Item2,Item3,Item4 will also be there.
    }

      

0


source


You can try dynamically:

    private static dynamic methodTuple()
    {
        return new { Name = "Nick", Age = "Twenty" }; 
    }

      

... but returning a specific type or structure is better, as mentioned.

-4


source







All Articles