0

I want to override -- operator for MyString class. It should find the shortest word in string. Here is code:

class MyString
{
    private string data;
    public string Data
    {
        get { return data; }
        set { data = value; }
    }

    public MyString(string s)
    {
        Data = s;
    }

    public MyString(MyString s)
    {
        Data = s.Data;
    }

    public static MyString operator --(MyString s)
    {
        var words = s.Data.Split();
        int l = 99999, ind = 0;
        for (int i = 0; i < words.Length; i++)
        {
            if (words[i].Length < l)
            {
                ind = i;
                l = words[i].Length;
            }
        }
        MyString result = new MyString(words[ind]);
        return result;
    }
}

When I try to use it like this:

    MyString s1, shortest;
    s1 = new MyString("one two three");
    shortest = s1--;
    Console.WriteLine(shortest.Data);

it returns "one two three" instead of "one". How can I fix it?

st_dec
  • 142
  • 1
  • 11

1 Answers1

3
var x = foo--;

is post-decrement, i.e. similar to:

var x = foo;
foo--;

You might want pre-decrement, i.e.

var x = --foo;

which is similar to:

foo--;
var x = foo;

Either way: it inappropriately changes foo, which you probably don't want. If you do:

shortest = --s1;
Console.WriteLine(shortest.Data);
Console.WriteLine(s1.Data);

You'll see that s1.Data is also now "one".

I suggest instead:

shortest = s1.GetShortestWord();
Console.WriteLine(shortest.Data);
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900