Skip to content

Latest commit

 

History

History
48 lines (36 loc) · 3.25 KB

user-defined-conversion-operators.md

File metadata and controls

48 lines (36 loc) · 3.25 KB
title description ms.date f1_keywords helpviewer_keywords
User-defined explicit and implicit conversion operators - provide conversions to different types
Learn how to define custom implicit and explicit type conversions in C#. The operators provide the functionality for casting an object to a new type.
11/28/2022
explicit_CSharpKeyword
implicit_CSharpKeyword
explicit
implicit
explicit keyword [C#]
implicit keyword [C#]
conversion operator [C#]
user-defined conversion [C#]

User-defined explicit and implicit conversion operators

A user-defined type can define a custom implicit or explicit conversion from or to another type. Implicit conversions don't require special syntax to be invoked and can occur in various situations, for example, in assignments and methods invocations. Predefined C# implicit conversions always succeed and never throw an exception. User-defined implicit conversions should behave in that way as well. If a custom conversion can throw an exception or lose information, define it as an explicit conversion.

User-defined conversions aren't considered by the is and as operators. Use a cast expression to invoke a user-defined explicit conversion.

Use the operator and implicit or explicit keywords to define an implicit or explicit conversion, respectively. The type that defines a conversion must be either a source type or a target type of that conversion. A conversion between two user-defined types can be defined in either of the two types.

The following example demonstrates how to define an implicit and explicit conversion:

[!code-csharpimplicit an explicit conversions]

Beginning with C# 11, you can define checked explicit conversion operators. For more information, see the User-defined checked operators section of the Arithmetic operators article.

You also use the operator keyword to overload a predefined C# operator. For more information, see Operator overloading.

C# language specification

For more information, see the following sections of the C# language specification:

See also