• Home
  • Insight
  • Blog
  • Business
  • Entertainment
  • Health
  • Politics
  • Shop
    • Gift Shop
    • Value Shop
    • Store
    • Bargain Shop
    • Discount
  • Sports
  • Tech
  • Travel
  • USA
  • Video
  • World
    • Asia
    • Africa
    • South America
    • North America
    • Europe
    • Oceania
Friday, November 20, 2026
No Result
View All Result
Subscribe Now
  • Home
  • Insight
  • Blog
  • Business
  • Entertainment
  • Health
  • Politics
  • Shop
    • Gift Shop
    • Value Shop
    • Store
    • Bargain Shop
    • Discount
  • Sports
  • Tech
  • Travel
  • USA
    Texas Execution Prolonged As Staff Encounter Difficulties Finding Vein, Inmate Reinaldo Dennes Reports Pain

    Texas Execution Prolonged As Staff Encounter Difficulties Finding Vein, Inmate Reinaldo Dennes Reports Pain

    Trump’s Deal Turns Sour as Voters Withdraw Support

    Trump’s Deal Turns Sour as Voters Withdraw Support

    FAA Administrator Takes Responsibility as Mullin Faces Tough Questions Over Nationwide Ground Stop

    FAA Administrator Takes Responsibility as Mullin Faces Tough Questions Over Nationwide Ground Stop

    Mary Peltola Emerges Victorious in Alaska Senate Race, Making History for Democrats

    Mary Peltola Emerges Victorious in Alaska Senate Race, Making History for Democrats

    Stranded in Conflict: Palestinians Navigate the Tenuous Balance of War and Peace Amid Ceasefire Efforts

    Stranded in Conflict: Palestinians Navigate the Tenuous Balance of War and Peace Amid Ceasefire Efforts

    Trump Administration Revokes Pay Increase for Head Start Educators

    Trump Administration Revokes Pay Increase for Head Start Educators

    Unexpected Triumph: Gay Candidates Achieve Unforeseen Victories in Challenging Races

    Unexpected Triumph: Gay Candidates Achieve Unforeseen Victories in Challenging Races

    Microsoft Outlook Experiences Prolonged Outage Affecting Users Nationwide

    Microsoft Outlook Experiences Prolonged Outage Affecting Users Nationwide

    Gunfire Erupts in D.C.: Authorities Search for Suspect Amid Rising Concerns Over Public Safety

    Gunfire Erupts in D.C.: Authorities Search for Suspect Amid Rising Concerns Over Public Safety

  • Video
  • World
    • Asia
    • Africa
    • South America
    • North America
    • Europe
    • Oceania
The Insight Post
  • Home
  • Insight
  • Blog
  • Business
  • Entertainment
  • Health
  • Politics
  • Shop
    • Gift Shop
    • Value Shop
    • Store
    • Bargain Shop
    • Discount
  • Sports
  • Tech
  • Travel
  • USA
    Texas Execution Prolonged As Staff Encounter Difficulties Finding Vein, Inmate Reinaldo Dennes Reports Pain

    Texas Execution Prolonged As Staff Encounter Difficulties Finding Vein, Inmate Reinaldo Dennes Reports Pain

    Trump’s Deal Turns Sour as Voters Withdraw Support

    Trump’s Deal Turns Sour as Voters Withdraw Support

    FAA Administrator Takes Responsibility as Mullin Faces Tough Questions Over Nationwide Ground Stop

    FAA Administrator Takes Responsibility as Mullin Faces Tough Questions Over Nationwide Ground Stop

    Mary Peltola Emerges Victorious in Alaska Senate Race, Making History for Democrats

    Mary Peltola Emerges Victorious in Alaska Senate Race, Making History for Democrats

    Stranded in Conflict: Palestinians Navigate the Tenuous Balance of War and Peace Amid Ceasefire Efforts

    Stranded in Conflict: Palestinians Navigate the Tenuous Balance of War and Peace Amid Ceasefire Efforts

    Trump Administration Revokes Pay Increase for Head Start Educators

    Trump Administration Revokes Pay Increase for Head Start Educators

    Unexpected Triumph: Gay Candidates Achieve Unforeseen Victories in Challenging Races

    Unexpected Triumph: Gay Candidates Achieve Unforeseen Victories in Challenging Races

    Microsoft Outlook Experiences Prolonged Outage Affecting Users Nationwide

    Microsoft Outlook Experiences Prolonged Outage Affecting Users Nationwide

    Gunfire Erupts in D.C.: Authorities Search for Suspect Amid Rising Concerns Over Public Safety

    Gunfire Erupts in D.C.: Authorities Search for Suspect Amid Rising Concerns Over Public Safety

  • Video
  • World
    • Asia
    • Africa
    • South America
    • North America
    • Europe
    • Oceania
No Result
View All Result
No Result
View All Result
Home Tech

How to use implicit and explicit operators in C#

by Theinsightpost
February 1, 2023
in Tech
0 0
0
How to use implicit and explicit operators in C#


One of the lesser known features of C# is the ability to create implicit and explicit user-defined type conversions, meaning we have support for both implicit and explicit conversions of one type to another type. We also have explicit and implicit operators, meaning some operators require an explicit cast and some operators don’t.

This article talks about these explicit and implicit conversion operators and how we can work with them in C#. To work with the code examples provided in this article, you should have Visual Studio 2022 installed in your system. If you don’t already have a copy, you can download Visual Studio 2022 here.

Create a console application project in Visual Studio

First off, let’s create a .NET Core console application project in Visual Studio. Assuming Visual Studio 2022 is installed in your system, follow the steps outlined below to create a new .NET Core console application project in Visual Studio.

  1. Launch the Visual Studio IDE.
  2. Click on “Create new project.”
  3. In the “Create new project” window, select “Console App (.NET Core)” from the list of templates displayed.
  4. Click Next.
  5. In the “Configure your new project” window shown next, specify the name and location for the new project.
  6. Click Next.
  7. In the “Additional information” window shown next, choose “.NET 7.0 (Standard Term Support)” as the framework version you want to use.
  8. Click Create.

Following these steps will create a new .NET Core console application project in Visual Studio 2022. We’ll use this project to work with type conversions in the subsequent sections of this article.

What are implicit and explicit type conversions?

An implicit type conversion is one that is done by the runtime automatically. You don’t need to cast to any specific type. Here is an example that illustrates an implicit conversion:

int x = 100; 
double d = x;

However, note that the following code will not compile.

double d = 100.25;
int x = d;

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

csharp implicit conversion error IDG

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

The error indicates that the runtime will not convert a double to an int without explicit type casting. This type of type casting is known as explicit type casting because you must write explicit code to perform the type casting.

You can fix the non-compilable code snippet by specifying an explicit type cast of double to int as shown in the code snippet below.

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

The above code will compile successfully without any errors.

Create model and DTO classes in C#

Let’s now understand how we can use implicit and explicit conversions in user-defined data types, i.e., classes.

Consider the following two classes.

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

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

In the preceding code snippet, the Author class is the model, i.e., it represents the Author entity. The AuthorDto class represents the data transfer object of the Author class. A data transfer object is a container of data used to pass data between the layers of an application.

Convert model to DTO and vice versa in C#

The following two methods show how you can convert an Author instance to an AuthorDto instance and convert and AuthorDto instance to an Author instance.

public AuthorDto ConvertAuthorToAuthorDto(Author author)
    {
        AuthorDto authorDto = new AuthorDto
        {
            Id = author.Id.ToString(),
            FirstName = author.FirstName,
            LastName = author.LastName
        };
        return authorDto;
    }

public Author ConvertAuthorDtoToAuthor(AuthorDto authorDto)
    {
        Author author = new Author
        {
            Id = Guid.Parse(authorDto.Id),
            FirstName = authorDto.FirstName,
            LastName = authorDto.LastName
        };
        return author;
    }

If you need to write such conversion code for several classes in your application, you will not only find it cumbersome but also your code will not have proper readability. Here is where implicit and explicit conversion operators come in.

Use the implicit conversion operator in C#

A better way to achieve 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 methods to convert an instance of one type to another. The code is much more straightforward.

The following code snippet shows how you can take advantage of the implicit operator to convert an Author instance to an AuthorDto instance.

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

And here’s how you can use the implicit operator to convert an Author instance to an AuthorDto instance:

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

Use the explicit conversion operator in C#

The following code snippet shows how you can take advantage of the explicit operator to convert an Author instance to an instance of AuthorDto class.

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

In this case you’ll need an explicit cast to convert an Author instance to an AuthorDto instance as shown in the code snippet given below.

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

Note you cannot have both implicit and explicit operators defined in a class. If you have defined an implicit operator, you will be able to convert objects both implicitly and explicitly. However, if you have defined an explicit operator, you will be able to convert objects explicitly only. This explains why you cannot have both implicit and explicit operators in a class. Although an implicit cast is more convenient to use, an explicit cast provides better clarity and readability of your code.

Copyright © 2023 IDG Communications, Inc.



Source link

ShareTweetSend
Previous Post

King Charles III won’t appear on new Australian bank notes

Next Post

MCA T10 Bash 2023 Points Table and Team Standings

Related News

Uber Launches Pilot Program for Safe Children’s Rides with Trusted Drivers
Tech

Uber Launches Pilot Program for Safe Children’s Rides with Trusted Drivers

November 20, 2026
Exploring Innovations: A Breakthrough in Living Liver Technology, a Lucrative Battery Partnership, and the Surge of AI Excitement
Tech

Exploring Innovations: A Breakthrough in Living Liver Technology, a Lucrative Battery Partnership, and the Surge of AI Excitement

November 19, 2026
Microsoft’s Satya Nadella Reveals Strategic Rationale Behind Layoff of 60,000 Employees
Tech

Microsoft’s Satya Nadella Reveals Strategic Rationale Behind Layoff of 60,000 Employees

November 19, 2026
Cybercriminals Embrace Innovative AI Tool for Streamlined Hacking Operations
Tech

Cybercriminals Embrace Innovative AI Tool for Streamlined Hacking Operations

November 18, 2026
Next Post
MCA T10 Bash 2023 Points Table and Team Standings

MCA T10 Bash 2023 Points Table and Team Standings

Discussion about this post

Subscribe To Our Newsletters

    Customer Support


    1251 Wilcrest Drive
    Houston, Texas
    77042 USA
    Call-832.795.1420
    e-mail – news@theinsightpost.com

    Subscribe To Our Newsletters

      Categories

      • Africa
      • Africa-East
      • African Sports
      • American Sports
      • Arts
      • Asia
      • Australia
      • Business
      • Business Asia
      • Business- Africa
      • Canada
      • Defense
      • Education
      • Egypt
      • Energy
      • Entertainment
      • Europe
      • European Soccer
      • Finance
      • Germany
      • Ghana
      • Health
      • Insight
      • International
      • Investing
      • Japan
      • Latest Headlines
      • Life & Living
      • Markets
      • Mobile
      • Movies
      • New Zealand
      • Nigeria
      • Politics
      • Scholarships
      • Science
      • South Africa
      • South America
      • Sports
      • Tech
      • Travel
      • Travel-Africa
      • UK
      • USA
      • Weather
      • World
      No Result
      View All Result

      Recent News

      Discover the Perfect Atmos Community for You!

      Discover the Perfect Atmos Community for You!

      November 20, 2026
      Claire Sweeney Faces Heartbreak Following the Passing of Ex-Partner Ricky Hatton

      Claire Sweeney Faces Heartbreak Following the Passing of Ex-Partner Ricky Hatton

      November 20, 2026
      Democrats Poised to Amplify Investigation into Trump’s Obamacare Rollback Following Major Victory

      Democrats Poised to Amplify Investigation into Trump’s Obamacare Rollback Following Major Victory

      November 20, 2026
      White House Cybersecurity Official Resigns Amid Rising Threats to National Security

      White House Cybersecurity Official Resigns Amid Rising Threats to National Security

      November 20, 2026
      • Home
      • Advertise With Us
      • About Us
      • Corporate
      • Consumer Rewards
      • Forum
      • Privacy Policy
      • Social Trends

      Theinsightpost ©2026 | All Rights Reserved. Theinsightpost is an Elnegy LLC company, registered in Texas, USA

      Welcome Back!

      Login to your account below

      Forgotten Password?

      Retrieve your password

      Please enter your username or email address to reset your password.

      Log In

      Add New Playlist

      We are using cookies to give you the best experience on our website.

      You can find out more about which cookies we are using or switch them off in .

      No Result
      View All Result
      • Home
      • Insight
      • Blog
      • Business
      • Entertainment
      • Health
      • Politics
      • Shop
        • Gift Shop
        • Value Shop
        • Store
        • Bargain Shop
        • Discount
      • Sports
      • Tech
      • Travel
      • USA
      • Video
      • World
        • Asia
        • Africa
        • South America
        • North America
        • Europe
        • Oceania

      Theinsightpost ©2026 | All Rights Reserved. Theinsightpost is an Elnegy LLC company, registered in Texas, USA

      The Insight Post
      Powered by  GDPR Cookie Compliance
      Privacy Overview

      This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.

      Strictly Necessary Cookies

      Strictly Necessary Cookie should be enabled at all times so that we can save your preferences for cookie settings.

      Cookie Policy

      More information about our Cookie Policy