C
C#8mo ago
CodeGeek

Basic calculator application

Hello I just made this application but im not sure if there is a better or more optimized way to make this kind of program. If anyone would be interesting in helping it would be much appreciated!
No description
11 Replies
Denis
Denis8mo ago
There is no need to do a convert to string on the Console.Readline It returns a string right away
Jimmacle
Jimmacle8mo ago
what happens if i type "potato" instead of a number? also, instead of saying "error try again" if they don't choose a valid operator, tell them they chose an invalid operator
Denis
Denis8mo ago
Also Convert.To.... isn't the model way of parsing strings to other types
Jimmacle
Jimmacle8mo ago
$tryparse
MODiX
MODiX8mo ago
When you don't know if a string is actually a number when handling user input, use int.TryParse (or variants, e.g. double.TryParse)
if(int.TryParse("123", out int number))
{
var total = number + 1;
Console.WriteLine(total); // output: 124
}
if(int.TryParse("123", out int number))
{
var total = number + 1;
Console.WriteLine(total); // output: 124
}
TryParse returns a bool, where true indicates successful parsing. Remarks: - Avoid int.Parse if you do not know if the value parsed is definitely a number. - Avoid Convert.ToInt32 entirely, this is an older method and Parse should be preferred where you know the string can be parsed. Read more here
Denis
Denis8mo ago
Use, e.g., dynamic.TryParse(...)
Jimmacle
Jimmacle8mo ago
(i think you mean decimal)
Denis
Denis8mo ago
Ah yes Sorry
CodeGeek
CodeGeekOP8mo ago
Thank you guys for all your feedback Ill make sure to make those changes!
Angius
Angius8mo ago
Protip when it comes to dynamic: use the banned APIs analyzer to blanket-ban it from every project you start
Servator
Servator8mo ago
Also don't forget DRY (Don't Repeat Yourself) principle Instead of using Console.WriteLine() for each operation Just output at the end of code
Want results from more Discord servers?
Add your server