Type Conversions in C#

Photo by Suzanne D. Williams on Unsplash

Implicit Conversions

If we want to assign an object belonging to class X to an object belonging to class Y in C# language, our code will not be compiled. In spite of this information, how can we assign the following int type object to a long type object?

int integerValue = 42;
long longValue = integerValue;

Explicit Conversions

Can we assign an object of type long to an object we define as int? The answer is both yes and no. If we look at the code block below, we can see that we cannot make a direct assignment as in the previous example.

long longValue = 42;
int intValue = (int) longValue;

Usage Scenerio

There were many value objects such as UserId, ProjectId, UserPassword in a project that I tried to develop by using the DDD concept. Most of these were structures with values ​​such as Guid and string. While creating these value objects, I was first creating an object of Guid type as in the example below. Then I was generating an object of UserId type by giving the value to my constructor method.


In scenarios where we do unconscious type conversion, we also do a similar operation to method overload. For example, let’s assume that we have a method that takes an object of UserId type and manipulates it. We can also call this method with an object of Guid type. The reason for this is the C# language’s ability to activate the method by automatically converting the Guid object to the UserId type.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Adem Catamak

Adem Catamak

var software = ConvertFrom(caffeine)