• 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
Thursday, July 30, 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
    TX Rep. Brandon Gill Mocks James Talarico Over Fauci Action Figure Post

    TX Rep. Brandon Gill Mocks James Talarico Over Fauci Action Figure Post

    NBA players are ‘being taught’ to flop

    NBA players are ‘being taught’ to flop

    Industry was warned for years about chemical ‘runaway’ dangers. Then came near-catastrophe in O.C.

    Industry was warned for years about chemical ‘runaway’ dangers. Then came near-catastrophe in O.C.

    Trump administration seeks government-wide NDAs to stop leaks : NPR

    Trump administration seeks government-wide NDAs to stop leaks : NPR

    Dog discharges shotgun inside truck, striking woman at Nebraska traffic light

    Dog discharges shotgun inside truck, striking woman at Nebraska traffic light

    Toshifumi Suzuki, Japan’s ‘God’ of Convenience Stores, Dies at 93

    Toshifumi Suzuki, Japan’s ‘God’ of Convenience Stores, Dies at 93

     Judge Sanctioned CoreCivic for Destroying Video in ICE Death Suit

     Judge Sanctioned CoreCivic for Destroying Video in ICE Death Suit

    Suspect dead after opening fire near White House security checkpoint, Secret Service says

    Suspect dead after opening fire near White House security checkpoint, Secret Service says

    Trump trashes Colbert’s high-rated finale as “no ratings”

    Trump trashes Colbert’s high-rated finale as “no ratings”

  • 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
    TX Rep. Brandon Gill Mocks James Talarico Over Fauci Action Figure Post

    TX Rep. Brandon Gill Mocks James Talarico Over Fauci Action Figure Post

    NBA players are ‘being taught’ to flop

    NBA players are ‘being taught’ to flop

    Industry was warned for years about chemical ‘runaway’ dangers. Then came near-catastrophe in O.C.

    Industry was warned for years about chemical ‘runaway’ dangers. Then came near-catastrophe in O.C.

    Trump administration seeks government-wide NDAs to stop leaks : NPR

    Trump administration seeks government-wide NDAs to stop leaks : NPR

    Dog discharges shotgun inside truck, striking woman at Nebraska traffic light

    Dog discharges shotgun inside truck, striking woman at Nebraska traffic light

    Toshifumi Suzuki, Japan’s ‘God’ of Convenience Stores, Dies at 93

    Toshifumi Suzuki, Japan’s ‘God’ of Convenience Stores, Dies at 93

     Judge Sanctioned CoreCivic for Destroying Video in ICE Death Suit

     Judge Sanctioned CoreCivic for Destroying Video in ICE Death Suit

    Suspect dead after opening fire near White House security checkpoint, Secret Service says

    Suspect dead after opening fire near White House security checkpoint, Secret Service says

    Trump trashes Colbert’s high-rated finale as “no ratings”

    Trump trashes Colbert’s high-rated finale as “no ratings”

  • 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

A fundamental flaw leaves LLMs strikingly vulnerable to attack
Tech

A fundamental flaw leaves LLMs strikingly vulnerable to attack

July 30, 2026
Google engineer charged with insider trading after making .2M on Polymarket
Tech

Google engineer charged with insider trading after making $1.2M on Polymarket

May 27, 2026
The Osprey Farpoint 40 Has Been My Go-To Travel Bag for 8 Years
Tech

The Osprey Farpoint 40 Has Been My Go-To Travel Bag for 8 Years

May 27, 2026
Source: AI inference provider Baseten is in talks to raise B at a post-money valuation of B, up from B after its 0M Series E announced in January (The Information)
Tech

Source: AI inference provider Baseten is in talks to raise $1B at a post-money valuation of $11B, up from $5B after its $300M Series E announced in January (The Information)

May 26, 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
      • UK
      • USA
      • Weather
      • World
      No Result
      View All Result

      Recent News

      US Navy to overhaul torpedo stockpile under new two-war strategy

      US Navy to overhaul torpedo stockpile under new two-war strategy

      July 30, 2026
      Free Cloud Computing Course | AWS Re/Start Program 

      Free Cloud Computing Course | AWS Re/Start Program 

      July 30, 2026
      Thirty Years Later

      Thirty Years Later

      July 30, 2026
      Announcing Codemagic Patch: an open-source CodePush rebuild for React Native

      Announcing Codemagic Patch: an open-source CodePush rebuild for React Native

      July 30, 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