Ram
Ram

Reputation: 11644

How to set a value from another class

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?

Upvotes: 4

Views: 8030

Answers (5)

Hans Olsson
Hans Olsson

Reputation: 55009

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

Upvotes: 3

Klaus Byskov Pedersen
Klaus Byskov Pedersen

Reputation: 120937

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;}
} 

Upvotes: 0

Prutswonder
Prutswonder

Reputation: 10064

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; }
}

Upvotes: 2

Len
Len

Reputation: 2145

you mean something like this?

   public int Test { get; set; }

Upvotes: 0

Petar Minchev
Petar Minchev

Reputation: 47373

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:)

Upvotes: 0

Related Questions