Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# 7.x using a short name for tuple type

Tags:

c#

tuples

By using Tuples, I can massively simplify my code by replacing a lot of structs. Except there is one catch here stops me from such practice.

How to preserve the names for each item in the Tuple when creating a "using" shortcut? I have created the examples in the code below with my comments.

/* This way is desired because it keeps the naming for each item in the Tuple, 
but incorrect grammar for C# 7.3 */
using Employee = (string Name, DateTime StartTime, DateTime LeaveTime, 
int Id, double Payment);

/* This way is the correct grammar for C# 7.3, but I lost all the names for the items, 
and I have to use Item1, Item2 and so on.... */
using Employee = Tuple<string, DateTime, DateTime, int, double>;

public class TestFunc
{
    public Employee GetEmployee()
    {
        Employee value; // I know it is an errorous usage here.
        value.Name = "Steve"; // Just want to make an example.
        value.StartTime = new DateTime();
        value.EndTime = new DateTime();
        return value;
    }
}
like image 343
Xu Li Avatar asked Jul 27 '18 04:07

Xu Li


1 Answers

Not much more typing:

struct Employee {public string Name; public DateTime StartTime; public DateTime LeaveTime; 
public int Id; public double Payment}

Leaving aside the usual discussion about the evil of mutable structs1; there's plenty that can be done to make this better, once you've taken this step. But this is a minimal way of doing almost what you asked for (except it really does have these named fields rather than compiler trickery).

You haven't shown all of your usage for it so you may also want to implement other constructors and Deconstruct methods.


1Since if you're working with ValueTuples already, you're already working with mutable structs, and hopefully already wary of them.

like image 85
Damien_The_Unbeliever Avatar answered Oct 03 '22 12:10

Damien_The_Unbeliever