tags:

views:

66

answers:

5

Its said that property should not be "Set" only (Code analysis rule CA1044 )and it should be "Get" as well. What should i do if I need to set value to a variable from some other class?

The will keep changing so I cannot pass it through constructor.

Shall I 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?

A: 

Who said a property should not use only set accessor? I don't see a design flaw in it. If there is one, I will be glad to learn something new:)

Petar Minchev
I think it can be confusing in the client code when there's a property that can't be read, it doesn't feel right to me. The "official" reason would be analysis warning CA1044 - http://msdn.microsoft.com/en-us/library/ms182165.aspx
ho1
@ho - Thanks for the CA rule. I forgot to mention that in question. I have updated the question now.
Ram
@ho +1, Thanks for the info.
Petar Minchev
A: 

you mean something like this?

   public int Test { get; set; }
SirLenz0rlot
+2  A: 

You can use a public setter and a private getter, in case you need to access the variable in its own class.

class B {
   public int test { private get; set; }
}
Prutswonder
This seems better alternative to me. But If I can set the value from that class itself then why should have private set? Is it just to have both Set and Get in the property?
Ram
There is no point in setting a value, if you are not going to use that value somewhere. If it's only to trigger an action, then you are better off writing a method, as proposed in the accepted answer.
Prutswonder
+2  A: 

I'd agree with that it's a bit confusing with write only properties (from a client of the class points of view), so I try to avoid them and instead create a set method of some kind.

The way recommended by Microsoft also seems to be to rewrite it to a method (or make it read and write if suitable): http://msdn.microsoft.com/en-us/library/ms182165.aspx

ho1
A: 

Your example does not really 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 property an autoproperty (where the framework generates the backing field), like so:

class B 
{ 
   public int Test{get; set;}
} 
klausbyskov