C# conversions: Implicit VS Explicit

After many years programming in .NET, you may have already realized that the framework allows us, in a very simple way, to make conversions between different types of data.

Conversions can be of 2 types 👇

  • Implicit Conversions
  • Explicit Conversions

Implicit conversions are for which it is not necessary to indicate the conversion in parentheses (…).

double variable = 10;

In the code we assign a variable of type double a value of type int:

But the compiler doesn’t tell us anything and lets us continue working as if nothing had happened. This is known as an implicit conversion.

Instead, if we do the following 👇

int variable = 10.0;

The compiler will give us an error indicating that an implicit conversion from double to int cannot be done, and tells us to use an explicit conversion

There is no mystery about it, simply this problem can be fixed by putting (int) in front of 10.0 👇

int variable = (int) 10.0;

Placing the type of data to which we want to convert it in parentheses is called explicit conversion. What this means is that with this syntax we are explicitly indicating to the compiler that we want to convert one type of data into a different one.

At this point you could perfectly tell me that this would also work 👇

double variable = (double) 10;

Apparently it does the same as if we don’t put (double) in front of it.

So… where is the difference? 🤔

The only difference between implicit and explicit conversions has to do with whether or not there is a risk of that information being lost.

If we go to the first case (without parentheses), it is an implicit conversion. The value of the litetal int does not matter as if we write double since there will be no risk of losing the information as it is a type of greater capacity.

On the contrary, if we go to the second case, we are forced to do an explicit conversion. This works because a double object can contain values ​​that a smaller capacity int type cannot represent.

Let’s take an example 👇

int variable = (int) 10.5;

An integer type cannot contain decimals, so it will truncate 10.5 to 10, thus losing information.

How we can create our own conversions

Usually the conversions of the Framework are more than enough for the needs that arise. However, there may be many cases where it would be more useful to define our own implicit and explicit conversions. The .NET platform provides us with an easy way to do it.

To create a conversion between two types, we simply have to write the corresponding operator, either implicit or explicit.

We are going to create an imaginary scenario in which we have to manage the temperatures so that the degrees can change between Celsius and Fahrenheit.

Let’s create the code 👇

class Temperature
    public float Degrees  get; set; 
class Celsius : Temperature
    public Celsius(float temp)
      Grados = temp;
  class Fahrenheit : Temperature
      public Fahrenheit(float temp)
    Grados = temp;

Now with this code we have the possibility of writing methods so that we do the conversion between them, and which we call each time.

class Temperature

  public float Degrees  get; set; 
  public Celsius ToCelsius()
    return new Celsius(((5.0f / 9.0f) * (this.Degrees - 32)));
  public Fahrenheit ToFahrenheit()
    return new Fahrenheit(((9.0f / 5.0f) * this.Degrees + 32));

Celsius cel = new Celsius(10);
Fahrenheit far = cel.ToFahrenheit();
Celsius cel2 = far.ToCelsius();

This works, but we will have to call the corresponding method each time and this makes the code very messy.

If we want to do an implicit conversion, we simply have to define a static operator with the static implicit operator.

We go back to our example 👇

class Temperature
    public float Degrees  get; set; 
  class Celsius : Temperature
  public Celsius(float temp)
    Grados = temp;
  public static implicit operator Fahrenheit(Celsius c)
      return new Fahrenheit((9.0f / 5.0f) * c.Degrees + 32);
  class Fahrenheit : Temperature
    public Fahrenheit(float temp)
      Grados = temp;
  public static implicit operator Celsius(Fahrenheit fahr)
  return new Celsius((5.0f / 9.0f) * (fahr.Degrees - 32));

Celsius cel = new Celsius(10);
Fahrenheit far = cel;
Celsius cel2 = far;

We can see that to each class we add an implicit conversion operator for the other related class, and after that, we just implicitly perform the conversions.

What we gain from this is a much cleaner code that meets the conditions for implicit conversions.

If we want to do it differently… 🤔

Let’s imagine that we have an application that has to manage the teachers and students of a school.

Let’s see it better 👇

public class Person
    public string Name  get; set; 
  public class Pupil : Person
    public string Class get; set; 
    public List<int> IdsCourse  get; set; 
  public class Teacher : Person
    public string Class  get; set; 
    public int IdContract  get; set; 

If at some point a student becomes a teacher or vice versa, we will need to use a conversion to reuse the data. As in this case, we are going to lose information since the different classes do not handle the same information.

Therefore the conversion will have to be explicit 👇

public class Person

public string Name  get; set; 

public class Pupil : Person

public string Class  get; set; 
public List<int> IdsCourse  get; set; 
public static explicit operator Teacher(Pupil alum)

return new Teacher Name = alum.Name, Class= alum.Class, IdContract = -1 ;

public class Teacher: Person

public string Class get; set; 
public int IdContract  get; set; 
public static explicit operator Pupil (Teacher prof)

return new Pupil Name = prof.Name, Class= prof.Class, IdsCourse = new List<int>() ;

Teacher teacher = new Teacher  Name = "Juan", Class= "Programming", IdContract = 10 ;
Pupil student = (Pupil)teacher;
Teacher teacher2 = (Teacher)student;

✅ Conclution:

Marking a conversion as implicit or explicit must strictly meet the criteria of whether there is a risk of information loss. It may be the case that today you consider the loss of information that occurs to be negligible, but that at some point it is not.

If you have marked the conversion as implicit, anyone who uses it directly assumes that there is no information loss.

If there is later and the failure is in that conversion, it can be a big headache, even more so if the code is part of a library and the person who uses it cannot see the code, so always think about it before defining the conversion. 🤗

Source link

Clean Architecture Solution Template

I’ve become a huge fan of the Clean Architecture pattern when working on .NET API’s. I won’t go into a ton of detail here, as there are a lot of great resources out there on the subject already, including from the person that I first learned it from, Jason Taylor. If you’re unfamiliar with this pattern, do yourself a favor and check out this presentation by Jason from the GOTO 2019 conference:

But at the 10,000 foot level, an API project using the Clean Architecture pattern has 4 separate projects (along with the necessary unit testing projects):

  • Domain – This project is meant to hold the domain entities of the application. The classes in this project map to the data tables or records in whatever data store the application is configured to use.
  • Application – This project contains the business logic and rules that make the application as a whole run as it’s supposed to. It directly references the Domain project, but no other projects within the solution.
  • Infrastructure – This project contains the implementation of any logic that needs to communicate with outside entities, such as a database, the file system, other HTTP API’s, and so forth. It references the Application project to gain access to application contracts that it will then implement for accessing the aforementioned external entities.
  • Api – This is the front-end of the application, and provides the start-up code and the API endpoint entry points.

Solution Template Nuget Package

I’ve created a Nuget package called StaticSphere.CleanArchitecture.Api, and published it to Nuget.org. You can install it using the following command:

dotnet new --install StaticSphere.CleanArchitecture.Api

Once installed, you can create a new solution by running the following command:

dotnet new clean-arch <<parameters>>

When executed, you’ll get a full .NET 6 ASP.NET API solution that contains the following folder structure (assuming you named to the solution HelloWorld):

  • src
    • HelloWorld.Api
    • HelloWorld.Application
    • HelloWorld.Domain
    • HelloWorld.Infrastructure
  • tests
    • HelloWorld.Api.Tests
    • HelloWorld.Application.Tests
    • HelloWorld.Infrastructure.Tests

The projects are all .NET 6 applications with nullable references types and implicit usings enabled. The unit testing projects use Xunit out of the box. There are also support files such as .gitignore, .editorconfig, etc.

There are parameters that can be passed to the dotnet new command that alter the solution that is created:

  • –includeTests – Determines if the test projects should be included or not. Default value: true
  • –skipRestore – If specified, skips the automatic restore of the project on create. Default value: false
  • –useStartup – Determines if the API project should use Startup.cs instead of the newer Minimal API style Program.cs file. Default value: false
  • –includeEF – If set, the created solution will include Entity Framework Core, and will be configured to use the specified provider (only these providers are currently supported)
    • postgres – Adds Postgres Entity Framework configuration
    • sqlserver – Adds SQL Server Entity Framework configuration

Open Source

The Nuget package that contains the solution template is completely free and open source, and is MIT licensed. The Nuget package can be found here, and the source code for the template can be found here. If you have any suggestions, or would like to contribute to the template, please let me know!

Source link

.Net Core vs NodeJS (Resumen)

Hola Amigos y bienvenidos a este vs entre dos tecnologías, en esta ocasion haremos un resumen de los que hemos venido Hablando.

¿NodeJS o .Net Core?

Como lo hemos dicho anteriormente, hablar de cada una y confrontarlas no es que queramos hacerte usar una o la otra, por el contrario, que tengas un panorama más amplio sobre cada una y los proyectos que pueden realizar en cada uno para que así completes el proyecto sin problemas, cada una tiene sus bondades para un proyecto en específico que la otra no posea y viceversa, queda a tu elección cual usar. Solamente ten en cuenta que para el lado web, tanto a nivel de cliente como servidor NodeJS es bastante rapido lo que lo hace un gran candidato y ganador es ese ambito, mientras que en proyectos transaccionales .Net Core se lleva el premio.


.Net Core NodeJS
Es Multiplataforma Es multiplataforma
Sistema de almacenamiento en cache confiable Base de Código única y potente
Implementacion y mantenimiento flexible y sencillo Escalabilidad e implementación seguras


.Net Core NodeJS
Soporte relacional de objetos limitado Bloqueo de E/S
La brecha entre el lanzamiento y la estabilidad Estandarización de librerias.

Tipos de Proyectos

.Net Core NodeJS
Web, mismas que pueden ser desplegadas en Windows, Linux o Mac OS Aplicaciones de chat en tiempo real
Aplicaciones con Docker, en cualquiera de las nubes ya sea (Azure, AWS o GCP) Aplicaciones web
Aplicaciones de Escritorio UWP lo que permite que tus apps sean ejecutadas en Windows 10, XBOX y HoloLens Servicios de API Rest
IA Streaming de datos
Desarrollo de juegos Aplicaciones complejas de una sola Página

En resumen, cada una de ellas está en continuo desarrollo para el soporte de distintos proyectos y arquitecturas, queda de tí implementarlos de la mejor forma.

Me despedido, y espero les agrade este vs, espero sus comentarios.

Imagen por Marius Niveri en Unsplash

Source link