English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Example Sharing of Explicit and Implicit Usage in C#

Today, while reviewing an old project, I came across some strange code.

if (dto.Payment == null) continue;
var entity = entries.FirstOrDefault(e => e.LedgerEntryID == dto.LedgerEntryID);
dto.Payment = entity?.Payment;

Among them, dto.Payment is an instance of the PaymentDTO class, entity?.Payment is an instance of the Payment class, and the PaymentDTO class and the Payment class do not have a subclass and superclass relationship, so there is no implicit conversion between subclasses and superclasses.

It is strange that the Visual Studio compiler did not prompt any compilation errors.

After opening the definition of the PaymentDTO class, the following method signature was found.

public static implicit operator PaymentDTO(Payment payment)

From the method signature, this is the override of the operator of PaymentDTO type, but it is not the one I used to use+,-,*,/, ==, etc.

After consulting MSDN, I learned that implicit and explicit are a pair of conversion operators.

Implicit and Explicit

Implicit

The Implicit keyword is used to declare implicit user-defined type conversion operators. It can achieve2Different implicit conversions between classes, which improves the readability of the code. However, it should be noted that after using the implicit conversion operator, the compiler will skip exception checking, so the implicit conversion operator should never cause exceptions and never lose information, otherwise some unexpected problems may occur at runtime.

For example, the definitions of PaymentDTO and Payment at present are as follows

public class Payment
  {
     public decimal Amount { get; set; }
  }
  public class PaymentDTO
  {
     public string AmountString { get; set; }
  }

If you need to implicitly convert Payment to PaymentDTO, you only need to declare the implicit conversion operator of PaymentDTO

public class PaymentDTO
    {
      public string AmountString { get; set; }
public static implicit operator PaymentDTO(Payment payment)
      {
        return new PaymentDTO
        {
AmountString = payment.Amount.ToString("C",2")
        };
      }
    }

When calling, it is only necessary to assign directly

class Program
    {
      static void Main(string[] args)
      {
PaymentDTO dto = new Payment { Amount = 1 };
        Console.WriteLine(dto.AmountString);
        Console.Read();
      }
    }

Explicit

The Explicit keyword is used to declare user-defined type conversion operators that must be called through conversion. Unlike implicit conversions, explicit conversion operators must be called through conversion; if an explicit conversion is missing, an error will occur at compile time.

For example, now we change the conversion operator defined in the PaymentDTO class from Implicit to Explicit

public class PaymentDTO
    {
      public string AmountString { get; set; }
public static explicit operator PaymentDTO(Payment payment)
      {
        return new PaymentDTO
        {
AmountString = payment.Amount.ToString("C",2")
        };
      }
    }

At this point, since there is no explicit conversion in the Main method, the compiler fails and prompts Cannot implicitly convert type 'ExplicitImplicit.Payment' to 'ExplicitImplicit.PaymentDTO'. An explicit conversion exists (are you missing a cast?63;)

To compile the compiler, just make a display conversion

class Program
    {
      static void Main(string[] args)
      {
PaymentDTO dto = (PaymentDTO)new Payment { Amount = 1 };
        Console.WriteLine(dto.AmountString);
        Console.Read();
      }
    }

Summary

Implicit improves the readability of the code, but programmers need to ensure themselves that the conversion does not cause exceptions and does not lose information

Explicit can prevent the compiler from silently calling conversion operations that may produce unexpected consequences.

The former is easier to use, and the latter clearly indicates to everyone who reads the code that you want to convert the type

That's all the content we have sorted out for you about the explicit and implicit usage in C#. You can refer to more examples when learning, and thank you for your support of the yana tutorial.

Declaration: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (Please replace # with @ when sending an email to report abuse, and provide relevant evidence. Once verified, this site will immediately delete the infringing content.)

You May Also Like