One of the lesser identified options of C# is the flexibility to create implicit and explicit user-defined sort conversions, which means now we have help for each implicit and explicit conversions of 1 sort to one other sort. We even have explicit and implicit operators, which means some operators require an explicit forged and some operators don’t.

This article talks about these explicit and implicit conversion operators and how we will work with them in C#. To work with the code examples supplied in this text, it is best to have Visual Studio 2019 put in in your system. If you don’t have already got a duplicate, you possibly can obtain Visual Studio 2019 right here.

Create a console utility challenge in Visual Studio

First off, let’s create a .NET Core console utility challenge in Visual Studio. Assuming Visual Studio 2019 is put in in your system, observe the steps outlined beneath to create a brand new .NET Core console utility challenge in Visual Studio.

  1. Launch the Visual Studio IDE.
  2. Click on “Create new project.”
  3. In the “Create new project” window, choose “Console App (.NET Core)” from the listing of templates displayed.
  4. Click Next.
  5. In the “Configure your new project” window proven subsequent, specify the title and location for the brand new challenge.
  6. Click Create.

Following these steps will create a brand new .NET Core console utility challenge in Visual Studio 2019. We’ll use this challenge in the following sections of this text.

What are implicit and explicit sort conversions?

An implicit sort conversion is one that’s accomplished by the runtime robotically. You don’t want to forged to any particular sort. Here is an instance that illustrates an implicit conversion:

int x = 100; 
double d = x;

However, observe that the next code won’t compile.

double d = 100.25;
int x = d;

Here’s the error you will observe In Visual Studio on compilation of the above code snippet.

IDG

Figure 1. The compiler gained’t allow you to assign a double to an integer variable in C#.

The error signifies that the runtime won’t convert a double to an int with out explicit sort casting. This sort of sort casting is named explicit sort casting since you should write explicit code to carry out the sort casting.

You can repair the non-compilable code snippet by specifying an explicit sort forged of double to int as proven in the code snippet beneath.

int x = 100; 
double d = (int) x;

The above code will compile efficiently with none errors.

Create mannequin and DTO lessons in C#

Let’s now perceive how we will use implicit and explicit conversions in user-defined information varieties, i.e., lessons.

Consider the next two lessons.

 public class Author
    {
        public Guid Id { get; set; }
        public string FirstIdentify { get; set; }
        public string LastName { get; set; }
    }

 public class AuthorDto
    {
        public string Id { get; set; }
        public string FirstIdentify { get; set; }
        public string LastName { get; set; }
    }

In the previous code snippet, the Author class is the mannequin, i.e., it represents the Author entity. The AuthorDto class represents the information switch object of the Author class. A knowledge switch object is a container of information used to cross information between the layers of an utility.

Convert mannequin to DTO and vice-versa in C#

The following two strategies present how one can convert an Author occasion to an AuthorDto occasion and vice-versa.

public AuthorDto ConvertAuthorToAuthorDto(Author creator)
        {
            AuthorDto authorDto = new AuthorDto
            {
                Id = creator.Id.ToString(),
                FirstIdentify = creator.FirstIdentify,
                LastName = creator.LastName
            };
            return authorDto;
        }
        public Author ConvertAuthorDtoToAuthor(AuthorDto authorDto)
        {
            Author creator = new Author
            {
                Id = Guid.Parse(authorDto.Id),
                FirstIdentify = authorDto.FirstIdentify,
                LastName = authorDto.LastName
            };
            return creator;
        }

If you want to write such conversion code for a number of lessons in your utility, you’ll not solely discover it cumbersome but in addition your code won’t have correct readability. Here is the place implicit and explicit conversion operators come in.

Use the implicit conversion operator in C#

A greater manner to obtain the model-DTO conversions illustrated above is to use implicit and explicit operators. When you use implicit or explicit conversion operators, you don’t have to write cumbersome strategies to convert an occasion of 1 sort to one other. The code is far more simple.

The following code snippet exhibits how one can make the most of the implicit operator to convert an Author occasion to an AuthorDto occasion.

public static implicit operator AuthorDto(Author creator)
{
  AuthorDto authorDto = new AuthorDto();
  authorDto.Id = creator.Id.ToString();
  authorDto.FirstIdentify = creator.FirstIdentify;
  authorDto.LastName = creator.LastName;
  return authorDto;
}

And here is how one can use the implicit operator to convert an Author occasion to an AuthorDto occasion:

static void Main(string[] args)
{
   Author creator = new Author();
   creator.Id = Guid.NewGuid();
   creator.FirstIdentify = "Joydip";
   creator.LastName = "Kanjilal";
   AuthorDto authorDto = creator;
   Console.ReadKey();
}

Use the explicit conversion operator in C#

The following code snippet exhibits how one can make the most of the explicit operator to convert an Author occasion to an occasion of AuthorDto class.

public static explicit operator AuthorDto(Author creator)
{
  AuthorDto authorDto = new AuthorDto();
  authorDto.Id = creator.Id.ToString();
  authorDto.FirstIdentify = creator.FirstIdentify;
  authorDto.LastName = creator.LastName;
  return authorDto;
}

In this case you’ll want an explicit forged to convert an Author occasion to an AuthorDto occasion as proven in the code snippet given beneath.

static void Main(string[] args)
{
  Author creator = new Author();
  creator.Id = Guid.NewGuid();
  creator.FirstIdentify = "Joydip";
  creator.LastName = "Kanjilal";
  AuthorDto authorDto = (AuthorDto)creator;
  Console.ReadKey();
}

Note you can’t have each implicit and explicit operators outlined in a category. If you could have outlined an implicit operator, it is possible for you to to convert objects each implicitly and explicitly. However, when you have outlined an explicit operator, it is possible for you to to convert objects explicitly solely. This explains why you can’t have each implicit and explicit operators in a category. Although an implicit forged is extra handy to use, an explicit forged gives higher readability and readability of your code.

How to do extra in C#:

Copyright © 2021 IDG Communications, Inc.