Converting a model to a DTO with an operator in C#

I have a model class representing 1 entity for 1 table in the database, and I need to convert it into a DTO class to respond to the client. Usually you’d define a ToDto method to convert, or use automapper. But today I have another way, which is using the explicit operator.

Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
namespace ConsoleApp;

public class StudentDto
{
public string Name { get; set; }
public int Age { get; set; }

public override string ToString()
{
return $"Name: {Name}, Age: {Age}";
}
}

public class StudentModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int YOB { get; set; }

public static explicit operator StudentDto(StudentModel model)
{
return new StudentDto
{
Age = DateTime.Now.Year - model.YOB,
Name = $"{model.FirstName} {model.LastName}"
};
}
}

public class Program
{
static void Main(string[] args)
{
var studentModel = new StudentModel
{
YOB = 2000,
FirstName = "Nguyen",
LastName = "Van A"
};

// Using the explicit conversion
var studentDto2 = (StudentDto)studentModel;
Console.WriteLine(studentDto2);
}
}
 Comments
Comment plugin failed to load
Loading comment plugin