Updated on
A POCO (Plain Old CLR Object) is a C# class that doesn’t depend on any framework, and it can have behavior, though the .NET glossary uses the term more narrowly for data-only classes. A DTO (Data Transfer Object) only carries data from one place to another. So every DTO is a POCO, but not every POCO is a DTO.
We use these objects in everyday coding, often without being sure where one ends and the other starts. Our rule of thumb is to keep behavior in POCO domain classes and send DTOs over the wire. In a small API where the class has no behavior and nothing to hide, returning it directly works fine. Below, we define both and then build a small Web API that uses them together.
Let’s start.
What Is a POCO Class in C#?
POCO stands for Plain Old CLR Object, and many developers read it as Plain Old C# Object. It’s a class that doesn’t inherit from a framework base class and doesn’t reference a library to do its job. We can create one with new anywhere: in an endpoint, a console app or a unit test.
The name describes the style of the class, not what we use it for. That’s the main difference from a DTO, which is defined by its usage.
A POCO can have behavior. Methods that validate data or calculate a value are fine, as long as they’re plain C#. A POCO also has no naming conventions for its properties or methods.
Domain entities are the usual example. Microsoft’s .NET microservices guide implements its Order entity as a POCO class that “doesn’t have any direct dependency on Entity Framework Core or any other infrastructure framework.” EF Core can still map such a class to a table, because the mapping lives outside it.
What Is a DTO in C#?
A DTO, or Data Transfer Object, is a class whose only job is to carry data from one place to another. Martin Fowler’s pattern catalog describes it as an object that “carries data between processes in order to reduce the number of method calls.”
We use DTOs to connect different parts of our system. One of the most common cases is communication between a server and a client: an endpoint maps its domain objects to DTOs and returns those.
To pass DTOs across systems, they must be serializable. And since their only purpose is to transfer data, we shouldn’t put any logic or behavior inside them. A DTO should be easy to read and have only properties. If a class has methods with logic, it is not a DTO.
In C#, we usually write DTOs as records or as classes with auto-properties. Because a DTO depends on nothing, it is also a POCO, which is why developers confuse the two.
We often store some sensitive data in the database, so we don’t want to send it to the client. That’s where DTOs shine, we can map our domain objects to present only the data we need for specific use cases.
Immutability with DTOs
DTOs are built for transferring data. In most cases, the client or the receiver of a DTO should not be able to modify it. That’s where immutability comes in handy because we can enforce those rules on our DTOs.
In older versions of C# language, this was more complex to achieve since we had to create our properties as getters. To set data upon object creation, we could use parameterized constructors but then end up with long construction declarations.
Luckily, C# version 9 introduced out-of-the-box immutability with Records that we can use to enforce immutability on our DTOs.
The properties of a positional record are init-only. If a client tries to change one after the record is created, the code doesn’t compile. This snippet uses the PersonDetails record we build later in the article and is meant to fail:
var personDetails = new PersonDetails("Bruce", "Wayne", "DC Street 22", new DateTime(1972, 7, 8));
personDetails.Address = "Gotham Street 1";
error CS8852: Init-only property or indexer 'PersonDetails.Address' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor.
When we need a different value, we create a copy with a with expression:
var personDetails = new PersonDetails("Bruce", "Wayne", "DC Street 22", new DateTime(1972, 7, 8));
var movedPersonDetails = personDetails with { Address = "Gotham Street 1" };
Console.WriteLine(personDetails.Address);
Console.WriteLine(movedPersonDetails.Address);
DC Street 22 Gotham Street 1
The original keeps its address. Keep in mind that this immutability is shallow. A record can’t swap a List<string> property for a different list, but anyone holding the record can still add items to that list. The init keyword behind all of this works on regular classes too, as our article on init-only setters shows.
Do DTOs Need Encapsulation?
Since DTOs only transfer the data and don’t have any behavior, we don’t need to enforce encapsulation. That said, we can use fields instead of properties, or even readonly fields if we want to enforce immutability in that way.
However, our DTOs should always be serializable, and fields make that harder. System.Text.Json, the serializer ASP.NET Core uses for our endpoint’s JSON, skips public fields by default. Let’s try it with a DTO that has two fields:
public class PersonFieldDto
{
public string? FirstName;
public string? LastName;
}
Now we serialize it twice, once with the default options and once with IncludeFields turned on:
using System.Text.Json;
var personFieldDto = new PersonFieldDto { FirstName = "Bruce", LastName = "Wayne" };
Console.WriteLine(JsonSerializer.Serialize(personFieldDto));
Console.WriteLine(JsonSerializer.Serialize(personFieldDto, new JsonSerializerOptions { IncludeFields = true }));
{}
{"FirstName":"Bruce","LastName":"Wayne"}
The first call returns an empty object. The data only makes it into the JSON with IncludeFields or a [JsonInclude] attribute on each field. Properties need neither, so we stick with properties for our DTOs.
Naming Conventions for DTOs
In many cases, we use different suffixes when naming DTOs. One of the most common suffixes is the “DTO” itself. In that case, if we have a Person domain object, we would call our DTO PersonDTO. Sometimes we want to split our DTOs based on the different operations we perform. In such cases, there is a possibility that we will have GetPersonDTO, CreatePersonDTO, etc.
Another common naming suffix for DTOs is the word “Model”. Some may argue that the “DTO” suffix is too generic since it doesn’t reveal our class’s place in the architecture. When that is the case, we can use something like PersonViewModel which clearly states that it is used on the view layer of our architecture.
How Do We Use POCOs and DTOs in a Web API?
Now, let’s create some use cases in a .NET Web API project to learn how we can use DTOs and POCOs together.
Usage of POCOs
POCOs are frequently used as DDD (Domain Driven Design) entities to model state and behavior. With that, let’s create a domain folder inside our project with a new class:
public class Person
{
public Person(int id)
{
Id = id;
}
public int Id { get; private init; }
public string? FirstName { get; set; }
public string? LastName { get; set; }
public string? Address { get; set; }
public DateTime DateOfBirth { get; set; }
public string? JobTitle { get; set; }
public string DoWork()
{
return $"{JobTitle} doing his work!";
}
public bool IsAdult()
{
var today = DateTime.Today;
var age = today.Year - DateOfBirth.Year;
if (DateOfBirth.Date > today.AddYears(-age))
age--;
return age >= 21;
}
}
We can see that we have both properties and methods inside our class to describe behavior. IsAdult() takes one year off the age when this year’s birthday hasn’t come yet, so someone who turns 21 tomorrow isn’t an adult today. The important thing to note is that no external libraries or dependencies are used within the class.
That’s also what makes a POCO easy to test. A unit test creates a Person with new and calls IsAdult(), without a host or a database:
[Fact]
public void GivenPersonWhoTurns21Tomorrow_WhenCheckingIsAdult_ThenReturnFalse()
{
var person = new Person(4) { DateOfBirth = DateTime.Today.AddYears(-21).AddDays(1) };
Assert.False(person.IsAdult());
}
Secondly, let’s create a fake data store to retrieve the Person data:
public static class FakeDataStore
{
public static ICollection<Person> GetPersonDomainObjects()
{
return
[
new Person(1)
{
FirstName = "Bruce",
LastName = "Wayne",
Address = "DC Street 22",
JobTitle = "Batman",
DateOfBirth = new DateTime(1972, 7, 8)
},
new Person(2)
{
FirstName = "Tony",
LastName = "Stark",
Address = "Marvel Street 9",
JobTitle = "Iron-Man",
DateOfBirth = new DateTime(1968, 5, 5)
},
new Person(3)
{
FirstName = "Peter",
LastName = "Parker",
Address = "Marvel Street 87",
JobTitle = "Spider-Man",
DateOfBirth = new DateTime(1992, 2, 4)
},
];
}
}
Here we return three POCO Person objects to simulate the database data.
Usage of DTOs
Now, let’s create a DTO based on the Person class that we can use to transfer data from server to client:
public record PersonDetails(string FirstName, string LastName, string Address, DateTime DateOfBirth);
Here we use most of the properties from our POCO class, except Id, which we hide from the client, and JobTitle, which the client doesn’t need. This is a good example of how we can modify DTOs to fit our purposes.
Combination of DTOs and POCOs
Finally, let’s see the combination of DTOs and POCOs in our service class. To do that, let’s create an interface for the service implementation first:
public interface IPersonService
{
Task<ICollection<PersonDetails>> GetPersonDetailsData();
}
In the IPersonService interface we have one method for retrieving our PersonDetails DTOs.
Now, let’s add the Mapster package with dotnet add package Mapster and create the implementation for the GetPersonDetailsData() method in a PersonService class:
using Mapster;
public class PersonService : IPersonService
{
public Task<ICollection<PersonDetails>> GetPersonDetailsData()
{
var people = FakeDataStore.GetPersonDomainObjects();
var personDetailsDtos = people.Adapt<ICollection<PersonDetails>>();
return Task.FromResult(personDetailsDtos);
}
}
Here we set our POCOs to the people variable and then use the Adapt() method from Mapster to map the collection of Person POCOs to the collection of PersonDetails DTOs.
Then, we use the Task.FromResult() method to simulate the asynchronous behavior and return the data of DTOs.
Lastly, let’s register the service and create a Minimal API endpoint in our Program class to retrieve the data:
builder.Services.AddScoped<IPersonService, PersonService>();
var app = builder.Build();
app.MapGet("/people-details", async (IPersonService personService)
=> await personService.GetPersonDetailsData());
Now let’s run the app and call the endpoint on the http port that dotnet run prints (5001 in the sample):
curl http://localhost:5001/people-details
The response, formatted for reading:
[
{
"firstName": "Bruce",
"lastName": "Wayne",
"address": "DC Street 22",
"dateOfBirth": "1972-07-08T00:00:00"
},
{
"firstName": "Tony",
"lastName": "Stark",
"address": "Marvel Street 9",
"dateOfBirth": "1968-05-05T00:00:00"
},
{
"firstName": "Peter",
"lastName": "Parker",
"address": "Marvel Street 87",
"dateOfBirth": "1992-02-04T00:00:00"
}
]
Perfect, we got our PersonDetails DTO results. There’s no id and no jobTitle in the JSON, because the DTO doesn’t have them.
Should a Class Be a POCO or a DTO?
Most of the confusion comes from the overlap: a DTO is a POCO with a narrower job. Here’s how the two compare in the sample we just built:
| POCO | DTO | |
|---|---|---|
| Defined by | Its style: plain C#, no framework dependency | Its usage: carrying data between parts of a system |
| Behavior | Can have methods with logic, like IsAdult() | Properties only, no logic |
| Typical C# shape | Class with constructor, properties and methods | Positional record, or a class with auto-properties |
| Serializable | Not required | Required, and properties serialize by default where fields don't |
| Changes after creation | Whatever the domain rules allow | Usually none: init-only properties and with copies |
| In the sample | Person, with Id and JobTitle | PersonDetails, without Id and JobTitle |
| Where we use it | Domain entities, EF Core entities | API requests and responses, messages between services |
| How they relate | Not every POCO is a DTO | Every DTO is a POCO |
When a class does both jobs, for example a domain class returned straight from an endpoint, it’s a POCO doing a DTO’s job. That’s fine while the class has no behavior and no data to hide. Once it gains either, we split it the way Person and PersonDetails are split here. To map between the two we used Mapster, and when the data arrives as JSON instead, our article on JSON deserialization covers that direction. If the question is whether the DTO should be a record, a class or a struct, we compare all three in records, classes or structs.
Conclusion
We’ve learned the main aspects and differences between a POCO (Plain Old CLR Object) and a DTO (Data Transfer Object). We looked at a usage example of both and saw how they work together in a Web API project, with Mapster turning Person POCOs into PersonDetails DTOs.
The main conclusion is that DTOs should be used only for transferring data, without any logic or behavior. On the other hand, we should use POCOs to describe the behavior of our object without any third-party dependencies. By their definitions, all DTOs should be POCOs, because if a class is not a POCO, it cannot be a valid DTO. That said, we can see why developers confuse these two types.
However, the reverse is not true, because if that was the case, the two types would be equivalent. So, all DTOs are POCOs, but not all POCOs are DTOs.
Tested with .NET 11.0.0, Mapster 10.0.14 and xUnit 2.9.3.







This is by far the best explanation of these two concepts and their differences that I found on the web.
Thanks!
Shorther explanation here: https://stackoverflow.com/a/725365/804385
Hey Dmitry, thanks for reading the article!
Indeed, that is a great short explanation. In our article, we wanted to go a little deeper with use cases and examples.