0

I have a class with a property like this:

public class MyClass { private int MyProp { get; set; } 

and several methods that use MyProp. One methods sets it and all other methods read the value. What I'd like to do is once the value is set, make it so that other methods can't change its value.

Thanks for your suggestions.

6
  • Does the first method execute before all others? Commented Jan 18, 2012 at 21:46
  • Context? Why would you want to do that? Commented Jan 18, 2012 at 21:47
  • @Tudor: yes, it executes first. Commented Jan 18, 2012 at 21:47
  • @Ocelot20: I receive an object that needs to be updated in the DB. I first set the ID and then I do so work on the object and I want to make sure that nowhere in the process do we change the ID of the object we work with. Commented Jan 18, 2012 at 21:48
  • In that case, sounds like you want to set it in the constructor like some answers suggest. Commented Jan 18, 2012 at 21:51

5 Answers 5

5

You can add a private field that is set when the property value changes:

public class MyClass { private bool myPropSet = false; private int myProp; public int MyProp { get { return myProp; } set { if (!myPropSet) { myPropSet = true; myProp = value; } } } 
Sign up to request clarification or add additional context in comments.

Comments

2

The closest thing I can think of is setting it readonly, which allows you to assign it in the constructor and then it becomes, well, read only.

public class MyClass { private readonly int MyProp { get; set; } public MyClass(int prop) { MyProp = prop; // cannot be modified further } } 

2 Comments

The problem is that it's set at the constructor level. I don't get the value until after the object is instantiated.
Ahh, I see. Well, I think the other solutions will solve your problem. :)
1

Personally having a Property public setter in this case is not intuative. How would the caller know that the setter has been called before? How would they know the setter is set correctly without doing a get?

I would prefer this so the caller knows that the set was successful (if it cares)

public int MyProp { get; private set; } public bool InitMyProp(int value) { if(!_set) { MyProp = value; _set = true; return true; } return false; } 

Comments

0

You could change it into a conventional property instead of an automatic property, and then validate the setter:

public class MyClass { private int _myProp; private int MyProp { get { return _myProp; } set { if (_myProp == 0) _myProp = value else throw new Exception(); } } } 

Comments

0

See the readonly modifier, if you can set the value in your constructor.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.