Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private-setter properties in C# 3.0 object initialization

If I have the following code:

public class MyClass 
{ 
  public string myName { get; private set; } 
  public string myId { get; set; } 
} 

A private compiler-generated variable is created for the setter. I want the setter not to be accessible for object initialization only. But, how do I get to initially set the myName variable?

Reading about object initialization I found the following:

... it’s read-only and the private field representing the underlying storage has a compiler-generated name that we cannot use in a constructor to assign to it. The solution is to use [...] object initializers

The solution would be, then, to use:

MyClass mc = new MyClass { 
myName = "What ever", 
myId = "1234" 
};

But this ends up in a compiler error sayin that:

The property or indexer 'MyClass.MyClass.myName' cannot be used in this context because the set accessor is inaccessible

So, is there a way to achieve setting this value using object initialization? If there is, what is the correct way to do it?

like image 810
jluna Avatar asked Jul 13 '09 20:07

jluna


People also ask

What is private set in C?

Private setters allow you to create read-only public or protected properties. That's it.

What is get private set in C#?

The code for getters is executed when reading the value. Since it is a read operation on a field, a getter must always return the result. A public getter means that the property is readable by everyone. While the private getter implies that the property can only be read by class and hence is a write-only property.

What will happen if getters and setters are made private?

The reason for declaring the getters and setters private is to make the corresponding part of the object's abstract state (i.e. the values) private. That's largely independent of the decision to use getters and setters or not to hide the implementation types, prevent direct access, etc.

Should getters and setters be public or private?

Usually you want setters/getters to be public, because that's what they are for: giving access to data, you don't want to give others direct access to because you don't want them to mess with your implementation dependent details - that's what encapsulation is about.


1 Answers

Since C# 9.0 you can use init accessor which allows you to set property value only during initialization.

Declaration:

public class MyClass 
{ 
  public string myName { get; init; } 
  public string myId { get; set; } 
} 

The object initialization will work with this configuration:

MyClass mc = new MyClass 
{ 
  myName = "What ever", 
  myId = "1234" 
};

See more details here.

like image 159
Michał Jarzyna Avatar answered Oct 17 '22 11:10

Michał Jarzyna