How to set a value from another class

The aforesaid says that the property should not be only "Set" (code analysis rule CA1044), and it should also be "Get". What should I do if I need to set a value for a variable from another class?

The change will continue, so I can not pass it through the constructor.

Create a function for this as shown below?

class A { public void SetValue() { b = new B(); b.SetTest(10); } } class B { int test; public void SetTest(int value) { test = value; } } 

What are the other alternatives?

+4
source share
5 answers

I would agree that this only confuses the recording properties a bit (from the client of the viewpoint class), so I try to avoid them and instead create some kind of dialing method.

Recommended by Microsoft also seems to be to rewrite it to a method (or make it readable and writable): http://msdn.microsoft.com/en-us/library/ms182165.aspx

+3
source

You can use a public setter and a private recipient if you need to access a variable in your class.

 class B { public int test { private get; set; } } 
+2
source

Who says a property should not use only set accessor? I do not see a lack of design in it. If there is, I will be happy to learn something new :)

0
source

do you mean something like this?

  public int Test { get; set; } 
0
source

Your example does not make much sense, since you are not holding on to your instance of B , but you can do something like this:

 class A { private B b; public A() { this.b = new B(); } public void SetValue() { this.b.Test = 10; } } class B { int test; public int Test { get{ return this.test; } set{ this.test = value; } } } 

Another alternative is to make the Test autoproperty property (where the framework generates a support field), for example:

 class B { public int Test{get; set;} } 
0
source

Source: https://habr.com/ru/post/1309526/


All Articles