operator
 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. ArchiveDisclaimer

# operator (C# Reference)

Visual Studio 2005

Use the operator keyword to overload a built-in operator or to provide a user-defined conversion in a class or struct declaration.

## Example

The following is an extremely simplified class for fractional numbers. It overloads the + and * operators to perform fractional addition and multiplication, and also provides a conversion operator that converts a Fraction type to a double type.

```// cs_keyword_operator.cs
using System;
class Fraction
{
int num, den;
public Fraction(int num, int den)
{
this.num = num;
this.den = den;
}

public static Fraction operator +(Fraction a, Fraction b)
{
return new Fraction(a.num * b.den + b.num * a.den,
a.den * b.den);
}

public static Fraction operator *(Fraction a, Fraction b)
{
return new Fraction(a.num * b.num, a.den * b.den);
}

// user-defined conversion from Fraction to double
public static implicit operator double(Fraction f)
{
return (double)f.num / f.den;
}
}

class Test
{
static void Main()
{
Fraction a = new Fraction(1, 2);
Fraction b = new Fraction(3, 7);
Fraction c = new Fraction(2, 3);
Console.WriteLine((double)(a * b + c));
}
}
```

#### Output

`0.880952380952381`

## C# Language Specification

For more information, see the following sections in the C# Language Specification:

• 7.2.3 Unary operator overload resolution

• 7.2.4 Binary operator overload resolution

How to: Implement User-Defined Conversions Between Structs (C# Programming Guide)

#### Reference

C# Keywords
implicit (C# Reference)
explicit (C# Reference)

#### Concepts

C# Programming Guide

C# Reference

Show: