liz
liz

Reputation: 19

How to set a value for a private set in c#

So, I need to go through my code base and remove all the public setters and change them to private for immutable properties.

I know this will make it harder for me to set the values an I can do that through a constructor. Are there any other ways for me to set the value besides through a constructor?

The point is to limit the access on changing the value.

Upvotes: 0

Views: 4591

Answers (3)

BenCamps
BenCamps

Reputation: 1834

There are several methods that I use to create immutable properties in C#, when I also need to set that property outside of the constructor.

The first scenario is to throw an exception if the object is modified after being set

private object _myProperty;
public object MyProperty
{
   public get { return _myProperty; }
   public set
   {
      if(_myProperty == null) { _myProperty = value; }
      else { throw new InvalidOperationException("MyProperty can't be changed onece set"); }
   }
}

This method doesn't prevent errors before runtime but it can help you catch yourself when you're doing silly things.

Another method is to hide setters using an interface. By explicitly implementing an interface you can hide a property or method from a user unless they cast your class to that specific interface. This doesn't actually make your property immutable, but it helps protect properties from unintentional modification.

public interface MyInterface
{
   object MyProperty { get; }
} 

public interface MyInterfaceProtected
{
   object MyProperty { set; }
}

public class MyClass : MyInterFace, MyInterfaceProtected
{
   private object _myProperty;
   public object MyProperty { get {return _myProperty;} }
   object MyInterfaceProtected.MyProperty
   {
      set { _myProperty = value; }
   }
}

Upvotes: 1

user3210023
user3210023

Reputation: 164

private string _value;
public SetValue(string value)
{
   _value = value;
}

or

ctrl+. on property to encapsulate field

Upvotes: 1

Belurd
Belurd

Reputation: 782

It seems you are talking about C# 6 { get; }. Those properties are settable only from the constructor.

If you will define your property as { get; private set; } you will be able to set it from this class or in derived classes.

Upvotes: 1

Related Questions