Anjan Saha
Anjan Saha

Reputation: 57

Setting property in a class of the type used in the property of a different class

Pardon me if it is nave;

but i am trying to set a property in class SomeType;

public class SomeType<T>
{
    private T _value;

    public T Name
    {
        get;
        set;
    }

    public T Value
    {
        get
        {
            return _value;
        }
        set
        {
            _value = value;
        }
    }
}

in another;

private class Source
{

    public SomeType<String> value1
    {
        get
        {
            return new SomeType<String>();
        }

    }

}

In the Test method what i am trying out is simple;

Source source = new Source();
source.value1.Value = "Test";

but the Value is never "Test"? Am i missing my concepts?

Upvotes: 1

Views: 132

Answers (4)

Taylor Leese
Taylor Leese

Reputation: 52292

value1 always returns a new SomeType. This is why the answer is never "Test". The code below should fix your issue:

private class Source
{
    public SomeType<String> value1
    {
        get;
        set;
    }
}

source.value1 = new SomeType<string>() { Value = "Test" };

Upvotes: 0

Mark Seemann
Mark Seemann

Reputation: 233125

In Source.value1, you are creating a new instance of SomeType<string> every time the getter is accessed (in itself not a good coding idiom). The default value of string is null, so that's the value of the Value property, because it was never set to anything else.

In other words. this is expected.

Maybe you could share with us what it is you are trying to achieve?

Upvotes: 0

LukeH
LukeH

Reputation: 269278

You're returning a new SomeType<string> object every time you access the value1 property, so although you're correctly setting the Value property on that object, it means that the next time you access value1 you're getting an entirely new object.

See if this makes any difference:

private SomeType<string> _value1 = new SomeType<string>();
public SomeType<string> value1
{
    get
    {
        return _value1;
    }
}

Upvotes: 3

Matt Breckon
Matt Breckon

Reputation: 3374

You are returning a new instance of SomeType everytime you access the value1 property. When you check that Value is "Test" you are checking that it is "Test" on an entirely new object.

Upvotes: 3

Related Questions