Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# allow public incrementation of property, but not explicit seting

What I want to do is allow the public incrementation of an integer value within my class, but not allow it to be publicly set explicitly.

I know that I can create a function like this:

void IncrementMyProperty()

but I'd like to allow the user to just do this:

MyClass.Property++;

without allowing this:

MyClass.Property = <SomeInt>;

It's merely for convenience. I'm just wondering if there is any way to do it.


Here's an example:

class MyClass
{
    private int _count;

    public int Count
    {
        get { return _count; }
        private set { _count = value; }
    }

    public void AddOne()
    {
        _count++;
    }
}

class Program
{
    static void Main()
    {
        MyClass example;

        for (int i = 0; i < 10; i++)
            example.Count++;
    }
}

Obviously this won't compile. It's just to show what I'd like to do.

like image 393
OneHoopyFrood Avatar asked Feb 11 '23 22:02

OneHoopyFrood


2 Answers

Well, it's possible, but the solution is pretty ugly.

You can create a type that overloads the ++ operator, and make a property of that type where the setter does nothing. That will allow you to use the ++ operator on the property, but it's not possible to actually set the property using the property setter:

class MyValue {

  public int Value { get; private set; }

  public MyValue(int value) {
    Value = value;
  }

  public static MyValue operator ++(MyValue v) {
    v.Value++;
    return v;
  }

}

class MyClass {

  private MyValue _count = new MyValue(0);

  public MyValue Count {
    get { return _count; }
    set { }
  }

}

Usage:

MyClass c = new MyClass();
c.Count++;
Console.WriteLine(c.Count.Value); // outputs 1

So... using the ++ operator in that way is not a good solution. Normally you don't have a setter that does nothing, that will only be confusing. Having a method that increases the counter is not as short as writing ++, but it won't be confusing as long as you name it so that it's clear what it does.

like image 99
Guffa Avatar answered Feb 14 '23 11:02

Guffa


There's no way. MyClass.MyProperty++ literally translates to MyClass.MyProperty = MyClass.MyProperty + 1, which uses a "setter" and if you allow a "setter" accessor then you would allow, for example, MyClass.MyProperty = <any value>;

like image 26
Saturn K Avatar answered Feb 14 '23 12:02

Saturn K