0

It is not clear what exactly is Identity Conversion in C#. Microsoft says:

Identity conversion An identity conversion converts from any type to the same type. This conversion exists such that an entity that already has a required type can be said to be convertible to that type.

Because object and dynamic are considered equivalent there is an identity conversion between object and dynamic, and between constructed types that are the same when replacing all occurrences of dynamic with object.

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/conversions

It would be nice to see some examples in C# of such conversion with some custom types to understand what exactly it is, its limitations, and benefits comparing to other types of conversions.

usr2020
  • 324
  • 2
  • 8

2 Answers2

3

As stated in the quote in the question, it's just the conversion of type X to itself. I.e.,

string x = (string) "Hello";

or even just:

string x = "Hello";

It's essentially just a no-op conversion.

As noted, "This conversion exists such that an entity that already has a required type can be said to be convertible to that type." So essentially the justification the spec gives is that it makes it easier to write the spec; the writers can say "such-and-such expression X is implicitly converted to type Y" even if X is already Y.

As Andrew's answer notes, there's a special case with object and dynamic, as the latter is actually object at runtime.

(This answer originally noted the rationale from a similar language, Java, but I felt it was incomplete and the same things could be said about C# just based on the C# specification.)

Joe Sewell
  • 6,067
  • 1
  • 21
  • 34
2

If you want, for example, convert dynamic to object compiler will use an identity conversion to do that. From the compiler perspective, there is a difference between object and dynamic. But from the runtime perspective, they are exactly the same.

In other words, from the compiler perspective, you need conversion in this case, but this conversion is possible because these types are actually identical.

You can also look at this answer of Eric Lippert to another question.