question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Generate constructors for C# DTOs?

See original GitHub issue

When generating a DTO type for a C# client with NSwag, is it possible to generate a constructor which has parameters for each of the DTO’s properties?

Ideally:

  • [Required] properties would be mandatory constructor parameters and others would be optional with default values.
  • the parameterless constructor required by Json.Net (marked [JsonConstructor]) would be private / protected (or there would be an option for this).

For example, given this DTO definition:

"User": {
      "type": "object",
      "additionalProperties": false,
      "properties": {
        "Id": {
          "type": "string"
        },
        "Name": {
          "type": "string"
        }
      },
       "required": [ "Id" ]
}

…NSwag would generate something like this DTO type (in “Poco” mode):

public class User
{
    [JsonConstructor]
    protected User() {}

    public User(string id, string name = null)
    {
        this.Id = id;
        this.Name = name;
    }

    public string Id { get; set; } // Ideally these would be private set, or even readonly fields, but I won't push my luck!
    public string Name { get; set; }
}

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Comments:11 (4 by maintainers)

github_iconTop GitHub Comments

3reactions
ta-stott-oecommented, Oct 26, 2017

Hi @zuckerthoben, the purpose of the constructor is to ensure at compile-time that the required properties have a value. (Or at least make it harder not to supply a value).

For example, let’s say I’m going to POST a User (as described above) to my API using the NSwag-generated client. This constructor (and the inaccessibility of the parameterless constructor) tells me as a consumer of the API that I need to supply a value for Id. Otherwise, I could just write new User { Name = "Foo" }, send it off and receive a Bad Request from the API.

To continue the example, perhaps the API and client have now been updated and User has a new mandatory property, say DateOfBirth. It is desirable for this to cause a compiler error in my code and force me to start providing a value for that too.

I guess this pattern is more useful for data being sent to the API but I’d argue it also has value for response DTOs because it helps when creating expected objects for tests.

As for having many parameters, yes I would gladly use a constructor with 10+ parameters rather than having to figure out which of 10+ properties I need to set. Also, arguably a class with 10+ properties is too big and should probably be split up, but that is a different discussion.

I am currently implementing the constructors myself but it is quite laborious and likely to lead to omissions as the DTOs change.

Read more comments on GitHub >

github_iconTop Results From Across the Web

C# - Initialize DTOs in constructor or via properties?
My thoughts are that if your object serves as a means to transfer data (and therefore purely output/input in a sense), the better...
Read more >
C# Dto constructor and dependency injection
I would like to know what is the best practice in designing the constructors of DTO objects. say i have a Dto object...
Read more >
Generate constructors for C# DTOs? · Issue #1020
When generating a DTO type for a C# client with NSwag, is it possible to generate a constructor which has parameters for each...
Read more >
How to Achieve Immutable DTOs With C# | HackerNoon
What we have to do to make it slightly better is to define private fields and use a constructor. public class Person {...
Read more >
DTO Generator
All args constructor – Generates a constructor that accepts arguments for all fields of the DTO. equals() and hashCode() – Generates the equals()...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found