Lasse
Lasse

Reputation: 431

String property behaves really weird

I have a settings class like this:

public class Settings
{
    string resourcePath;
    public string ResourcePath {
        get {
            return resourcePath + "/";
        }
        set {
            resourcePath = value;
        }
    }

    string texturePath;
    public string TexturePath {
        get {
            string a = resourcePath + "/"; // This is just some debug stuff I did trying to find out wtf is going on
            string b = texturePath + "/";
            return a + b; // Breakpointing here shows that it is "Content/Textures/"
        }
        set {
            texturePath = value;
        }
    }

    public Settings ()
    {
        resourcePath = "Content";
        texturePath = "Textures";
    }

    public static Settings CurrentSettings = new Settings();
}

Then I try to get the TexturePath from it, like this:

string path = Settings.CurrentSettings.TexturePath + file;

The string returned by the property is "Content//Content/Textures//"

What am I missing here? Why does it do that? With my knowledge it should return Content/Textures/

Upvotes: 0

Views: 76

Answers (3)

Jonathan Wood
Jonathan Wood

Reputation: 67193

You haven't shown the code that produces the results you reported but the following code is highly suspect:

string resourcePath;
public string ResourcePath {
    get {
        return resourcePath + "/";
    }
    set {
        resourcePath = value;
    }
}

It always appends a forward slash on the getter but never removes it in the setter. So the following code:

x.ResourcePath = "abc";
x.ResourcePath = x.ResourcePath + "/def";
x.ResourcePath = x.ResourcePath + "/ghi";

Would set ResourcePath to "abc//def//ghi".

I suspect you are running into something like that.

Upvotes: 1

Dmitrii Dovgopolyi
Dmitrii Dovgopolyi

Reputation: 6301

Use Path.Combine to work with path.

string path = Path.Combine(Settings.CurrentSettings.TexturePath,file);

and no need to add "/" to your properties.

public string ResourcePath {
    get {
        return resourcePath;
    }
    set {
        resourcePath = value;
    }
}

Upvotes: 3

meilke
meilke

Reputation: 3280

You might not be balancing the / between the getter and the setter. And you probably are getting some property and then setting another with it - resulting in too many /'s.

Upvotes: 2

Related Questions