Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Export (0) Print
Expand All
Important This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here.

Conversion Operators (C# Programming Guide)

C# enables programmers to declare conversions on classes or structs so that classes or structs can be converted to and/or from other classes or structs, or basic types. Conversions are defined like operators and are named for the type to which they convert. Either the type argument to be converted, or the type of the result of the conversion, but not both, must be the containing type.

class SampleClass
{
    public static explicit operator SampleClass(int i)
    {
        SampleClass temp = new SampleClass();
        // code to convert from int to SampleClass...

        return temp;
    }
}

Conversion Operators Overview

Conversion operators have the following properties:

  • Conversions declared as implicit occur automatically when required.

  • Conversions declared as explicit require a cast to be called.

  • All conversions must be static.

Related Sections

See Also

Community Additions

ADD
Show:
© 2015 Microsoft