Reputation: 45
I am trying to set a variable whose value will be a percent (i.e. "20%") which would be a string, and will change based on the level of the element. To calculate the level I have an integer. I am trying to use the C# properties to get more used to them and practice, but am uncertain if what I am attempting is allowed.
public int Tier { get; set; } = 1;
private string _ContainerLeft {
get { return _ContainerLeft; }
set
{
int left = (( value - 1) * 2) + 10;
_ContainerLeft = left.ToString() + "%";
}
}
protected override void OnInitialized()
{
base.OnInitialized();
_ContainerLeft = Tier;
}
This is the code for the variable. I take the value passed in (an integer), do some math to calculate the base case and growth, then convert it to the final string.
However, I get errors that "value - 1" can't be performed on a string and int, and on the "Tier" at the bottom that it isn't of type string.
I realize there are plenty of ways around these (although I don't know the best) such as doing some .toString(), int.Parse(), and casting. But I am more concerned with if this is possible without type manipulation.
Upvotes: 0
Views: 702
Reputation: 7497
Fundamentally when you write _ContainerLeft = Tier
and int left = ((value -1) * 2)
you are trying to do maths with a mixture of integers and strings, which will not work in C#.
Languages like javascript will try to give you some sort of answer (even if it's not what you might expect) but you have to convert from one to another in some way.
Typically I would suggest you make container left a method, and call it using the integer value of Tier
public string ContainerLeft()
{
var left = ((Tier - 1) * 2) + 10;
return $"{left}%"; // string interpolation is nice
}
This will compile fine, and will react to changes in Tier
apart from the initial OnInitialized()
Upvotes: 1