Do while with int.TryParse - how?
I am trying to create a C-sharp program, that ask the user to pick a number between 1 and 3. It will then use that number to print one of three names I have in an array. This is how far I got:
I wanted the do-while to continue until the nubmerText is an actual number I can parse to Int, but also then be a valid number from 1-3 but I am kind of confused as to how to proceed.
21 Replies
It's easier to use a
while (true)
loop and break when it's valid.Unknown User•10mo ago
Message Not Public
Sign In & Join Server To View
Aha. I learned that for things like this we use do-while, but perhaps I can juust use while and a break?
Even better might be to put it in its own function and
return
I didn't learn about functions yet (will later) so now I am trying to master while, do while, and the int try parse
Something like this:
(trying to learn step by step, but yeah I didn't say that sorry :p )
I didn't see the var keyword before. Is it a mutable variable? (like
var
in javascript, instead of const
)Unknown User•10mo ago
Message Not Public
Sign In & Join Server To View
Ok great, so its not unsafe :D
Unknown User•10mo ago
Message Not Public
Sign In & Join Server To View
(other than mutablity, but I meant the scoping issues of var in JS)
Unknown User•10mo ago
Message Not Public
Sign In & Join Server To View
Hm, so we don't have an equivalent of java
final
or javascript const
to make something immutable? (or even Object.freeze in JS, or as const
in typescript)const
is a keyword in C#, as is readonly
. Both can be used to enforce some level of immutability.
const
should generally be used only for things that are truly constant and guaranteed to never change (things like the value of pi for example) because otherwise if you change the constant value in a library, the consumer won't actually see the changed value unless they recompile their code.
Just realized you can use pattern matching to make the code a little nicer...thanks
So
readonly
is how we can make something immutable
in best practiceWell, sort of.
Like, if you make a property read only it means that property can't be mutated. But the thing the property references might be mutable. Like if you have a readonly property that points to an array, you can still mutate the array contents.
Getting true immutability is (sometimes) a lot of work.
A readonly field of a ReadOnlyCollection<T> for instance.
I take it as I should just treat C# as a mutable OOP language :)
I am just used to functional programming principles, but I guess I have to let it go for C#
C# has a lot of nice support for functional programming approaches these days.
I wouldn't necessarily treat it as just for OOP. (I dislike OOP and generally don't use things like inheritance hierarchies, for instance.)
Ok thats great, I will probably learn about it in the future as I learn more
LINQ for example has a pretty functional design.