Hi, I'm struggling a little bit. I wrote a simple calculor for the operation + and want to check the input. int = num1 and so on //Type first number and check if input is a letter Console.WriteLine("Type first number:"); num1 = Convert.ToInt32(Console.ReadLine()); if (num1 == string) { Console.WriteLine(num1 + " Only numbers allowed"); } This doesn't work if (num1 = string) I get the error invalid expression. What's wrong? Thx for your help.
i don't program in c# but from the looks of it you convert your input to int immediately so it will never be string and also you may want to try num1.gettype() == typeof(String) or something similar for your data type check (you'll probably need to do a different check anyways because logically it is impossible for it to be true)
First string is a type and num1 is a variable of type int. You cannot compare these two. You should capture the input as a string and test/convert it to numeric. Here is an example for you to rewrite into your own code. You can use int instead of decimal. Code: string input = "2.0"; decimal number = decimal.MinValue; decimal.TryParse(input, out number); if(number != decimal.MinValue) // if the value changed then the input is valid. { // input is ok. }
Hi, also dont forget that to test equality you must use == whereas to give a variable a value, just use = .
Hello @Windows4live , as an independent C# developer I suggest you to study very well the programming language (no offense though) Foregoing code has few lines of code that doesn't make sense as stevemk14ebr mentioned earlier: -First of all if you want to define a variable in C# it ought to be like this int num; , NOT int = num; . In your case 'int' becomes a variable that has num as a value. -You converted the variable thus there will be a problem once a user input letters. -there is another option for casting in C# instead of using Covert object you can use int.Parse(Console.ReadLine()); Any question feel free to ask me either on private message or here! thank you and have a wonderful day!
The Convert.ToInt32() function will throw an exception when the string given can't be converted to an int. You can do 2 things: 1) use a try catch block with the convert and everything that should happen if ok in the try block. It will go to catch of it fails. 2) What I usually do is write an bool IsInt32(String str) method that also uses try catch but returns a boolean (to avoid mixing the exception stuff with your actual logic). This method usually goed into a Validator class or something like that.