This is a follow up from the article on Casting Custom Types To C# Built-In Types.
In the previous article we looked at how we would take a custom object like a Class or a Struct and cast it to a C# built-in like a bool. In this article we will look at how to cast from one custom type to another.
What we will be exploring here is much like what AutoMapper does.
For this part we will define two custom classes, intialize one, then try casting it to the second custom type. See code below
PersonDTO class implements the
IConvertible interface (I am showing only relevant method here). It takes takes a Type argument and returns a new object of that type; in this case a new
PersonEntity. See usage below:
when executed, the
ToType() method on
PersonDTO is called and returns a new
PersonEntity with the first and last name set.
We can add multiple if else statements in the
ToType() method to convert the
PersonDTO class to other types if need be. This gives us a way to convert between types in cases where we do not want to, or cannot bring in libraries like AutoMapper.