Situation: I have multiple Web service API calls that deliver object structures. Currently, I declare explicit types to bind those object structures together. For the sake of simplicity, here's an example:
[HttpGet]
[ProducesResponseType(typeof(MyType), 200)]
public MyType TestOriginal()
{
return new MyType { Speed: 5.0, Distance: 4 };
}
Improvement: I have loads of these custom classes like MyType
and would love to use a generic container instead. I came across named tuples and can successfully use them in my controller methods like this:
[HttpGet]
[ProducesResponseType(typeof((double speed, int distance)), 200)]
public (double speed, int distance) Test()
{
return (speed: 5.0, distance: 4);
}
Problem I am facing is that the resolved type is based on the underlying Tuple
which contains these meaningless properties Item1
, Item2
etc. Example:
Question: Has anyone found a solution to get the names of the named tuples serialized into my JSON responses? Alternatively, has anyone found a generic solution that allows to have a single class/representation for random structures that can be used so that the JSON response explicitly names what it contains.
You have a little bid conflicting requirements
Question:
Comment:
Based on above - you should stay with types you already have. Those types provide valuable documentation in your code for other developers/reader or for yourself after few months.
From point of readability
will be better then
From point of maintainability
Adding/removing property need to be done only in one place. Where with generic approach you will need to remember update attributes too.