1

I have an object ex: string str and I want to make it read-only after it changed its value twice as shown here

string str="hello world";
str="hello";
str="hi";
//good
str="sup";
//error

but I also want to be able to change the number of times value can be assigned to the object for example:

string str[limit 2]="hello world";
str="hello";
str="hi";
//good
str[limit++];
str="sup";
//good

is it possible?

1 Answers1

3

Not with a string, but it's quite easy to create a class with a property that provide you such control:

class IrregularVariableConstThingy
{
    private int _changeCount = 0;
    private string _value;

    public IrregularVariableConstThingy(int maxChangeCount)
    {
        MaxChangeCount = maxChangeCount;
    }

    public int MaxChangeCount {get;set;}

    public string Value {
        get {
            return _value;
        }
        set {
            if(_changeCount = MaxChangeCount)
            {
                throw new Exception("Now you can't change my value!");
            }
            _changeCount++;
            _value = value;
        }
    }
}

Please note this this implementation is not thread safe nor recommended, but it does demonstrate the basic concept.

Zohar Peled
  • 79,642
  • 10
  • 69
  • 121
  • Extra credit to whoever gives the link to where I stole the `Thingy` from. – Zohar Peled Jun 27 '19 at 17:50
  • Plus 1 for awesome class name: `IrregularVariableConstThingy`. – Idle_Mind Jun 27 '19 at 17:50
  • @Idle_Mind The Thingy suffix, unfortunately, is a stolen suffix... I think I'm going to start doing that at work too... – Zohar Peled Jun 27 '19 at 17:51
  • @ZoharPeled https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/how-to-declare-and-use-read-write-properties? –  Jun 27 '19 at 17:53
  • https://doc.artdatabankensoa.se/WebService/html/299ead04-f55d-a645-5559-afc6cd93fa25.htm i will get upvote if i get it right right? –  Jun 27 '19 at 18:09
  • @ZoharPeled https://softwareengineering.stackexchange.com/questions/355533/use-of-my-prefix-in-object-naming ? – Mustafa Gursel Jun 27 '19 at 18:10
  • @MustafaGursel nice try but no. I'm beginning to think it wasn't a good idea to ask this question in the comments. some mod will get angry for too much comments eventually.... – Zohar Peled Jun 27 '19 at 18:13
  • @avivgood1 I'm asking specifically about the `Thingy` suffix. – Zohar Peled Jun 27 '19 at 18:14
  • Well, the `Thingy` suffix idea came from [this comment.](https://stackoverflow.com/questions/1866794/naming-classes-how-to-avoid-calling-everything-a-whatevermanager#comment46818302_10422164) Totally agree with that unknown engineer. – Zohar Peled Jun 28 '19 at 08:58