Static Implicit Statement

I recently found this code:

public static implicit operator XElement(XmlBase xmlBase) { return xmlBase.Xml; } 

What does static implicit operator mean?

+81
operators c # implicit-conversion
Nov 25 '10 at 4:32
source share
3 answers

This is a conversion operator . This means that you can write this code:

 XmlBase myBase = new XmlBase(); XElement myElement = myBase; 

And the compiler will not complain! At run time, the conversion statement will be executed - passing myBase as an argument and returning the result of a valid XElement .

This is a way for you as a developer to tell the compiler:

"although they look like two completely unrelated types, there really is a way to convert from one to another, just let me handle the logic of how to do this.

+150
Nov 25 '10 at 4:38
source share

Such an implicit statement means that you can implicitly convert XmlBase to XElement .

 XmlBase xmlBase = WhatEverGetTheXmlBase(); XElement xelement = xmlBase; //no explicit convert here like: XElement xelement = (XElement)xmlBase; 
+8
Nov 25 '10 at 4:36
source share

This is an implicit conversion operator (as opposed to an Explicit statement that requires conversion syntax (type) )

+2
Nov 25 '10 at 4:37
source share



All Articles