mJay
mJay

Reputation: 743

c# Constructor and default values

I'm quite new to c#. Would like to have default values in my POCO. Path2 should depend on Path1 or extend it respectively.

public class Config
{
    public string Path1 { get; set; }
    public string Path2 { get; set; }
...
}

public Config()
{ Path1 = "testpath";
  Path2 = path1 + "bla";
  ...}

If now the user changes Path1 in the UI, I want Path2 also changed accordingly.

Config testconfig = new Config();
testconfig.Path1 = "changed";

But Path2 stays at "testpath bla" instead of "changed bla".

I guess I am missing something essential here. Could someone kick me in the right direction please?

Regards

Upvotes: 0

Views: 785

Answers (2)

Flat Eric
Flat Eric

Reputation: 8111

If the second part of Path2 is constant then you can use this:

public string Path2 
{
    get { return string.Format("{0}{1}", Path1, "bla"); }
}

instead of making Path2 an auto property.

EDIT:

According to the comments, maybe this is what you want

public class Config
{
    private string path1;
    private string path2;

    public string Path1 
    { 
        get { return path1;}
        set
        {
            path1 = value;
            Path2 = string.Format("{0}bla", value);
        }
    }

    public string Path2 
    {
        get { return path2; }
        set { path2 = value; }
    }

    public Config()
    {
        Path1 = "testpath";
    }
}

This will synchronize Path1 and Path2 any time when Path1 is set but also allows Path2 to be set completely separate

Upvotes: 3

Haedrian
Haedrian

Reputation: 4328

Strings don't work that way. When you append it, you're creating a separate new string (internally I mean), so your changes aren't going to 'propagate'.

To solve this for a fixed value, you can use Flat Eric's answer.

Having read your comments about a 'default value' and still make it avaliable for change, I'll propose something like this

private string _path2 = null;

public string Path1 {get;set;}
public string Path2 
{
get {

if (String.IsNullOrEmpty(_path2))
{
return Path1 + "bla"; //Or your default value
}
else 
{
return _path2;
}

}

set 
{
_path2 = value;
}

}

Upvotes: 1

Related Questions