Reputation: 113
I'm pretty new at C#, and coding in general, so there might be an obvious answer to this...
If I have a variable (X) that is equivalent to some other variables concatenated (Y and Z) (or added together, or whatever), how can I make X so that each time I use it, it gets any changes that Y and Z may have had.
Is that possible?
Here's my code. Here, I just kept updating the variable, but it'd be nice if I didn't have to keep doing that.
string prefix = "";
string suffix = "";
string playerName = "Player";
string playerNameTotal = prefix + playerName + suffix;
// playerNameTotal is made up of these 3 variables
Console.WriteLine(playerNameTotal); // Prints "Player"
prefix = "Super ";
playerNameTotal = prefix + playerName + suffix; // I want to not have to use this line
Console.WriteLine(playerNameTotal); // Prints "Super Player"
suffix = " is Alive";
playerNameTotal = prefix + playerName + suffix; // I want to not have to use this line
Console.WriteLine(playerNameTotal); // Prints "Super Player is Alive"
suffix = " is Dead";
prefix = "";
playerNameTotal = prefix + playerName + suffix; // I want to not have to use this line
Console.WriteLine(playerNameTotal); // Prints "Player is Dead"
I realize that there's probably a better way to accomplish this, but this isn't an important project. I'm more curious about the principle of the question than about how to solve this particular problem.
Thanks!
Upvotes: 1
Views: 136
Reputation: 241611
You want to use a class that encapsulates your model:
class PlayerName {
public string Prefix { get; set; }
public string Name { get; set; }
public string Suffix { get; set; }
public string PlayerNameTotal {
get {
return String.Join(
" ",
new[] { this.Prefix, this.Name, this.Suffix }
.Where(s => !String.IsNullOrEmpty(s))
);
}
}
}
Usage:
PlayerName playerName = new PlayerName {
Prefix = "",
Name = "Player",
Suffix = ""
};
Console.WriteLine(playerName.PlayerNameTotal);
playerName.Prefix = "Super";
Console.WriteLine(playerName.PlayerNameTotal);
playerName.Suffix = "is Alive";
Console.WriteLine(playerName.PlayerNameTotal);
playerName.Prefix = "";
playerName.Suffix = "is Dead";
Console.WriteLine(playerName.PlayerNameTotal);
Output:
Player
Super Player
Super Player is Alive
Player is Dead
Upvotes: 8
Reputation: 31133
Typically you can use a property for this
public string Salutation { get; set; }
public string Name { get; set; }
public string Greeting
{
get { return string.Format("{0}, {1}!", Salutation, Name); }
}
Upvotes: 1
Reputation: 160862
you could make your variable a property instead
public string X
{
get { return Y + Z; }
}
Upvotes: 5