Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static implicit operator

People also ask

What is an implicit operator?

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.

What is an implicit conversion C#?

In C#, you can perform the following kinds of conversions: Implicit conversions: No special syntax is required because the conversion always succeeds and no data will be lost. Examples include conversions from smaller to larger integral types, and conversions from derived classes to base classes.

What is C++ conversion operator?

Conversion Operators in C++ C++ supports object oriented design. So we can create classes of some real world objects as concrete types. Sometimes we need to convert some concrete type objects to some other type objects or some primitive datatypes. To make this conversion we can use conversion operator.

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

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. You also use the operator keyword to overload a predefined C# operator.


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

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

And the compiler won't complain! At runtime, the conversion operator will be executed - passing myBase in as the argument, and returning a valid XElement as the result.

It's a way for you as a developer to tell the compiler:

"even though these look like two totally unrelated types, there is actually a way to convert from one to the other; just let me handle the logic for how to do it."


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

XmlBase xmlBase = WhatEverGetTheXmlBase();
XElement xelement = xmlBase;   
//no explicit convert here like: XElement xelement = (XElement)xmlBase;

Another interesting usage is (which Unity did to check if an object (and therefore an instance of MonoBehavior) is null):

public static implicit operator bool (CustomClass c)
{
    return c != null;
}

Note that the code has to be inside the class (CustomClass in this case). That way you can do something like this:

void Method ()
{
    CustomClass c1 = null;
    CustomClass c2 = new CustomClass ();

    bool b1 = c1; // is false
    bool b2 = c2; // is true

    if (!c1 && c2)
    {
        // Do stuff
    }
}

Obviously the most notorious use might be using it to convert one of your classes to another of your classes. But using them with basic types is worth a consideration as well... and I see it mentioned quite rarely.


It's an implicit conversion operator (as opposed to an Explicit operator, which requires the (type) conversion syntax)