Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I use interface with explicit operator? [duplicate]

I'm just wondering if anyone knows the reason why you are not allowed to use interfaces with the implicit or explicit operators?

E.g. this raises compile time error:

public static explicit operator MyPlayer(IPlayer player) {  ... } 

"user-defined conversions to or from an interface are not allowed"

Thanks,

like image 669
theburningmonk Avatar asked Mar 12 '10 14:03

theburningmonk


People also ask

Can interface contain operators?

You can't define operators on interfaces because a class can implement multiple interfaces.

CAN interface have fields in C#?

An interface may not declare instance data such as fields, auto-implemented properties, or property-like events. By using interfaces, you can, for example, include behavior from multiple sources in a class. That capability is important in C# because the language doesn't support multiple inheritance of classes.

Which operator can be used to do type conversions in C#?

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.

What is implicit operator in C#?

The Implicit Operator According to MSDN, an implicit keyword is used to declare an implicit user-defined type conversion operator. In other words, this gives the power to your C# class, which can accepts any reasonably convertible data type without type casting.


1 Answers

Section 10.9.3 of the C# spec spells this out. The short version is that it's disallowed so that the user can be certain that conversions between reference types and interfaces succeed if and only if the reference type actually implements that interface, and that when that conversion takes place that the same object is actually being referenced.

Defining an implicit or explicit conversion between reference types gives the user the expectation that there will be a change in reference; after all, the same reference cannot be both types. On the other hand, the user does not have the same expectation for conversions between reference types and interface types.

User-defined conversions are not allowed to convert from or to interface-types. In particular, this restriction ensures that no user-defined transformations occur when converting to an interface-type, and that a conversion to an interface-type succeeds only if the object being converted actually implements the specified interface-type.

like image 79
Adam Robinson Avatar answered Oct 12 '22 16:10

Adam Robinson