Click here to Skip to main content
15,868,016 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Just curious if this could be like into 1 line or shorter. Basically, I'm making a text-based game and you can deposit 'cash' or 'coins' into the 'bank' and the code i have is:

 int deposited = int.Parse(msg[1]);
stats[user].Cash = stats[user].Cash - deposited;
stats[user].Bank = stats[user].Bank + deposited;


Just wondering if it could be shortened

What I have tried:

 int deposited = int.Parse(msg[1]);
stats[user].Cash = stats[user].Cash - deposited;
stats[user].Bank = stats[user].Bank + deposited;
Posted
Updated 29-Jul-18 21:54pm

1 solution

Marginally, but you should also make it better:
C#
int deposited = 0;
if (int.TryParse(msg[1], out deposited))
{
    stats[user].Cash -= deposited;
    stats[user].Bank += deposited;
}
else
{
    throw some error to indicate the input was not valid
}
 
Share this answer
 
v2
Comments
Eric Lynch 30-Jul-18 6:53am    
Building on this, to make it a bit shorter, I'd also invert the conditional and use an in-line variable (C# 7 or better)…

if (!int.TryParse(msg[1], out int deposited))
throw exception to indicate invalid input;

stats[user].Cash -= deposited;
stats[user].Bank += deposited;
George Swan 31-Jul-18 11:31am    
Isn't there a closing bracket missing from Richard's 'if' statement?
Richard MacCutchan 31-Jul-18 11:38am    
Uh oh, thanks, well spotted.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900