C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
With the explicit keyword, we implement the casting functionality as an operator method.
Example. This program introduces two classes: the Apartment class and the House class. Each also provides a public static explicit operator: the Apartment provides a House operator, and the House provides an Apartment operator.
C# program that uses explicit keyword using System; class Apartment { public string Name { get; set; } public static explicit operator House(Apartment a) { return new House() { Name = a.Name }; } } class House { public string Name { get; set; } public static explicit operator Apartment(House h) { return new Apartment() { Name = h.Name }; } } class Program { static void Main() { House h = new House(); h.Name = "Broadway"; // Cast a House to an Apartment. Apartment a = (Apartment)h; // Apartment was converted from House. Console.WriteLine(a.Name); } } Output Broadway
The explicit operators are implemented by constructing a new instance of the target type. They set the Name property from that of the original instance. Thus the Apartment or House is now of the opposite type but has the same data field.
Whenever you use a cast like (Apartment) or (House), this is an explicit cast. An implicit cast never uses this syntax. This example explicitly casts a House to an Apartment. Only one of the operators in the code is actually used.
Discussion. What is the point of the explicit operator? It provides a special syntax form for converting types. This can be more intuitive for certain operations, mainly ones that involve numeric types.
However: For classes such as Apartment or House, an explicit operator is not normally needed or useful.
And: The example here is for illustrative purposes. Explicit should be rarely used.
Summary. As with the implicit keyword, the explicit keyword is used to implement conversions. You should be careful with implementing conversions so that they are reversible and make sense. This operator is often not needed.
Tip: It is often better to implement conversions through helper methods so that the functionality is more obvious.