Thursday, April 23, 2015

C# Tuples

Tuples in C# provide a way for "one" object to have multiple types and values.  I use this a lot when I'm returning results from one method to another so I can check whether the call was successful (with a bool) and also return a value (like an error message) to the caller.

You use Tuples by specifying - through the use of generic type parameters - what the data types will be of each "item" in the tuple.  Each tuple can have seven items, and an eighth item that is another tuple.

In our home-grown ORM solution I've implemented tuples as the return type of the methods that map data from the database to the objects:



   1:  Tuple<TParent, TChild1, TChild2, TChild3, TChild4, TChild5, TChild6> Get
   2:              <TParent, TChild1, TChild2, TChild3, TChild4, TChild5, TChild6>(string sprocName,
   3:                                                                              List<SqlParameter> parameters = null,
   4:                                                                              string schema = "dbo",
   5:                                                                              CommandType commandType =
   6:                                                                                  CommandType.StoredProcedure)
   7:              where TParent : class
   8:              where TChild1 : class
   9:              where TChild2 : class
  10:              where TChild3 : class
  11:              where TChild4 : class
  12:              where TChild5 : class
  13:              where TChild6 : class;

This method will return a single object with a total of 7 items where there is one parent object that has six properties that are each a complex object.  When I invoke this method, I do so like this:



   1:  var data = Get<Person, List<Pet>, List<Car>, Person, List<Person>, House, Employer>("Person_GetDetails", new List<SqlParameter> {new SqlParameter("@ID", 12345)});
   2:   
   3:  var person = data.Item1;
   4:  person.Pets = data.Item2;
   5:  person.Cars = data.Item3;
   6:  person.Spouse = data.Item4;
   7:  person.House = data.Item5;
   8:  person.Employer = data.Item6;

This way I can pass back a single Person object from my repository method.  There are, of course, other uses, but this is a quick example of how to use tuples.

No comments:

Post a Comment