Skip to main content

Operator must be declared static and public

In This Article

CodeRush Classic shows the Operator must be declared static and public code issue if an operator is not marked public and static.

#Fix

Make the operator public and static.

#Purpose

Highlights the operator declarations, which would cause the User-defined operator must be declared static and public compilation error.

#Example

public class MyData
{
    public MyData(string name, List<string> data)
    {
        Name = name;
        Data = data;
    }
    public string Name { get; set; }
    public List<string> Data { get; set; }
    private MyData operator +(MyData d1, MyData d2)
    {
        string newName = String.Format("{0}&{1}", d1.Name, d2.Name);
        List<string> newData = d1.Data;
        newData.AddRange(d2.Data);
        return new MyData(newName, newData);
    }
}

Fix:

public class MyData
{
    public MyData(string name, List<string> data)
    {
        Name = name;
        Data = data;
    }
    public string Name { get; set; }
    public List<string> Data { get; set; }
    public static MyData operator +(MyData d1, MyData d2)
    {
        string newName = String.Format("{0}&{1}", d1.Name, d2.Name);
        List<string> newData = d1.Data;
        newData.AddRange(d2.Data);
        return new MyData(newName, newData);
    }
}