Related
Basically I'm trying to not let the user input string instead of an integer; but on line of code:
else if (Convert.ToString(result) == "")
I get an error.
Full code:
class Program
{
static void Main(string[] args)
{
Console.ForegroundColor = ConsoleColor.Red;
int calcKelvin = 273;
int calcFahren = 32;
int result = Convert.ToInt32(Console.ReadLine());
if (result == 0)
{
Console.WriteLine("Check it up on google!");
Console.Title = "I'M USELESS CONSOLE, YOU CAN NOW EXIT || I'M USELESS CONSOLE, YOU CAN NOW EXIT || I'M USELESS CONSOLE, YOU CAN NOW EXIT ||";
}
else if (Convert.ToString(result) == "")
{
Console.Write("Error, you can not convert a text");
}
else
{
Console.WriteLine("Kelvin = " + calcKelvin * result);
Console.WriteLine("Fahrenheit = " + calcFahren * result);
}
}
}
The safest way to get a number from a string is to use the TryParse method, because this method returns two values! The actual return type is a bool which indicates whether or not the string was successfully converted, and the other is an out parameter, which is of the type that we're converting to, and which gets set to the converted value (or is set to the default value of the type if the conversion fails).
For temperatures, we often deal with decimal numbers, so a double is probably a good type to store the result. So, we'll use double.TryParse.
Now, since we don't necessarily want to just quit if the user makes a mistake, we should probably do our conversion in a loop, so if it fails, we just ask the user to try again. And since this code will be used in other places as well, we can make a helper method that takes in a prompt that we display to the user, and returns the strongly-typed user response:
private static double GetDoubleFromUser(string prompt = null)
{
double result;
do
{
Console.Write(prompt);
} while (!double.TryParse(Console.ReadLine(), out result));
return result;
}
With this method, we can now just declare a double and assign it to the return value of the method above, like:
double userInput = GetDoubleFromUser("Enter a temperature: ");
Another thing we can correct in the code are the formulas used to do the conversions. A quick check online shows us that we add a number for kelvin and we do multiplication, division, and addition for Fahrenheit. We can calculate these values on the fly once we have the Celsius temperature from the user:
private static void Main()
{
double celcius = GetDoubleFromUser("Enter a Celcius temperature: ");
double fahrenheit = celcius * 9 / 5 + 32;
double kelvin = celcius + 273.15;
Console.WriteLine("Kelvin = " + kelvin);
Console.WriteLine("Fahrenheit = " + fahrenheit);
GetKeyFromUser("Done! Press any key to exit...");
}
Output
Convert.ToInt32 throws an exception if the input string is not a number. To fix that, you can use int.TryParse instead.
Example:
using System;
class Program
{
static void Main(string[] args)
{
Console.ForegroundColor = ConsoleColor.Red;
int calcKelvin = 273;
int calcFahren = 32;
int result;
bool isNum=int.TryParse(Console.ReadLine(),out result);
if (!isNum)
{
Console.Write("Error, you can not convert a text");
}
else if (result == 0)
{
Console.WriteLine("Check it up on google!");
Console.Title = "I'M USELESS CONSOLE, YOU CAN NOW EXIT || I'M USELESS CONSOLE, YOU CAN NOW EXIT || I'M USELESS CONSOLE, YOU CAN NOW EXIT ||";
}
else {
Console.WriteLine("Kelvin = " + calcKelvin * result);
Console.WriteLine("Fahrenheit = " + calcFahren * result);
}
}
}
I have multiple textboxes which asks the user to enter coordinates in the form (x,y) such as 5.5,7. I want to validate both the x and y coordinate to make sure that they are numbers. I was thinking that I could maybe split the coordinates by comma and validate each seperatly, but I think doing it that way would be long winded?.
private bool CoordinatesValidation()
{
bool status = true;
decimal temp;
foreach (TextBox tb in pointsPanel.Controls)
{
if (!decimal.TryParse(tb.Text, out temp))
{
errorProvider1.SetError(tb, "Invalid value, please enter a number!");
status = false;
}
else
{
errorProvider1.SetError(tb, "");
}
}
return status;
}
You can also use a regular expression to check if the format is as follows:
(\d+\.?\d+),\s*(\d+\.?\d+)
Which means:
Match on multiple decimals (\d+)
Match with a . dot in the middle
Match a comma between two decimals, with spaces, if there are any:
https://regexr.com/3vm63
Regex regex = new Regex(#"(\d+\.?\d+),\s*(\d+\.?\d+)");
Match match = regex.Match(tb.Text);
if(!match.Success)
{
//append the error message
}
You can leverage Object Orientation by introducing a Coordinate class that can handle the parsing and validation.
The advantage of this approach is that you can extend this class with additional functionality, e.g. by implementing IEquatable<Coordinate> or IComparable<Coordinate>.
public class Coordinate {
// Hidden parameterless ctor
private Coordinate() {}
// Public ctor requires two numbers
public Coordinate(decimal x, decimal y) : this() {
X = x;
Y = y;
}
public decimal? X { get; set; }
public decimal? Y { get; set; }
public const char AxisSeparator = ',';
public bool IsValid() {
return X.HasValue && Y.HasValue;
}
// Try to parse a coordinate text in the format "X.XX{AxisSeparator}Y.YY"
// If the parsing is not successful, returns false and error message as out variable
// Else returns true and the parsed Coordinate as out variable
public static bool TryParse(string input, out Coordinate result, out string errorMessage) {
errorMessage = string.Empty;
result = new Coordinate();
var parts = input.Split(AxisSeparator);
if (parts.Count() != 2) {
errorMessage = "Expected input in format 'X.XX, Y.YY' with '" + AxisSeparator + "' to separate X and Y coordinates.";
return false;
}
decimal x;
decimal y;
if (!decimal.TryParse(parts[0], out x)) {
errorMessage = "Expected input in format 'X.XX, Y.YY' with X.XX as number, but it was '" + parts[0] + "'.";
return false;
}
if (!decimal.TryParse(parts[1], out y)) {
errorMessage = "Expected input in format 'X.XX, Y.YY' with Y.YY as number, but it was '" + parts[1] + "'.";
return false;
}
result = new Coordinate(x, y);
return true;
}
public override string ToString() { return X.ToString() + AxisSeparator + " " + Y.ToString(); }
}
Usage example:
Coordinate coord = null;
string errorMessage = string.Empty;
var success = Coordinate.TryParse("3.14, 15.28b", out coord, out errorMessage);
if (!success) {
Console.WriteLine("Error: " + errorMessage);
Console.WriteLine("Coordinate is valid?: " + coord.IsValid());
}
else {
Console.WriteLine("Success: " + coord.ToString());
}
This usage (with the string "3.14, 15.28b") prints the message:
Error: Expected input in format 'X.XX, Y.YY' with Y.YY as number, but it was ' 15.28b'.
Coordinate is valid?: False
C# Fiddle for this example
Can't you mask the text boxes so that only numbers, or only a specified format, can be entered? Then you wouldn't have to check them after the fact. https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.maskedtextbox.mask?view=netframework-4.7.2
I made a custom method to print line and then read user input to assign it to double variable
here is my code :
double result = 0;
double a, b;
while (true)
{
if (Double.TryParse(GetValue("Enter value for a "), out a)
&& Double.TryParse(GetValue("Enter value for b "), out b))
{
result = a + b;
break;
}
else
{
Console.WriteLine("invalid value please try again..");
continue;
}
}
public static double GetValue(string input )
{
double z1;
double value;
Console.WriteLine(input);
value = Console.ReadLine();
z1 = value;
return z1;
}
but am facing an error which is that I can't convert 'double' to 'string'
. Can someone explain what am doing wrong ?
The problem is in the line
value = Console.ReadLine();
but you probably knew that already. ReadLine returns a string.
The easiest fix would be to return a string from GetValue, since you already try to parse it outside of the function:
public static string GetValue(string input )
{
Console.WriteLine(input);
return Console.ReadLine();
}
But an arguably cleaner solution would be to solve it in the function that asks the input and return a double from there:
double result;
double a, b;
a = GetValue("Enter value for a ");
b = GetValue("Enter value for b ");
result = a + b;
public static double GetValue(string input )
{
double value;
Console.WriteLine(input);
while (!Double.TryParse(Console.ReadLine(), out value))
{
Console.WriteLine("invalid value please try again..");
}
return value;
}
The reason I think this is slightly better, is because you isolate the logic of parsing into the function, so you need only one call to double.TryParse. Moreover, if someone would type an incorrect value for b, in your code they would need to start over with the value for a, where in my code, they just have to retry b.
I'd like to know on C# how to check if a string is a number (and just a number).
Example :
141241 Yes
232a23 No
12412a No
and so on...
Is there a specific function?
Look up double.TryParse() if you're talking about numbers like 1, -2 and 3.14159. Some others are suggesting int.TryParse(), but that will fail on decimals.
string candidate = "3.14159";
if (double.TryParse(candidate, out var parsedNumber))
{
// parsedNumber is a valid number!
}
EDIT: As Lukasz points out below, we should be mindful of the thread culture when parsing numbers with a decimal separator, i.e. do this to be safe:
double.TryParse(candidate, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out var parsedNumber)
If you just want to check if a string is all digits (without being within a particular number range) you can use:
string test = "123";
bool allDigits = test.All(char.IsDigit);
Yes there is
int temp;
int.TryParse("141241", out temp) = true
int.TryParse("232a23", out temp) = false
int.TryParse("12412a", out temp) = false
Hope this helps.
Use Int32.TryParse()
int num;
bool isNum = Int32.TryParse("[string to test]", out num);
if (isNum)
{
//Is a Number
}
else
{
//Not a number
}
MSDN Reference
Use int.TryParse():
string input = "141241";
int ouput;
bool result = int.TryParse(input, out output);
result will be true if it was.
Yep - you can use the Visual Basic one in C#.It's all .NET; the VB functions IsNumeric, IsDate, etc are actually static methods of the Information class. So here's your code:
using Microsoft.VisualBasic;
...
Information.IsNumeric( object );
int value;
if (int.TryParse("your string", out value))
{
Console.WriteLine(value);
}
This is my personal favorite
private static bool IsItOnlyNumbers(string searchString)
{
return !String.IsNullOrEmpty(searchString) && searchString.All(char.IsDigit);
}
Perhaps you're looking for the int.TryParse function.
http://msdn.microsoft.com/en-us/library/system.int32.tryparse.aspx
Many datatypes have a TryParse-method that will return true if it managed to successfully convert to that specific type, with the parsed value as an out-parameter.
In your case these might be of interest:
http://msdn.microsoft.com/en-us/library/system.int32.tryparse.aspx
http://msdn.microsoft.com/en-us/library/system.decimal.tryparse.aspx
int result = 0;
bool isValidInt = int.TryParse("1234", out result);
//isValidInt should be true
//result is the integer 1234
Of course, you can check against other number types, like decimal or double.
You should use the TryParse method for the int
string text1 = "x";
int num1;
bool res = int.TryParse(text1, out num1);
if (res == false)
{
// String is not a number.
}
If you want to validate if each character is a digit and also return the character that is not a digit as part of the error message validation, then you can loop through each char.
string num = "123x";
foreach (char c in num.ToArray())
{
if (!Char.IsDigit(c))
{
Console.WriteLine("character " + c + " is not a number");
return;
}
}
int.TryPasrse() Methode is the best way
so if the value was string you will never have an exception , instead of the TryParse Methode return to you bool value so you will know if the parse operation succeeded or failed
string yourText = "2";
int num;
bool res = int.TryParse(yourText, out num);
if (res == true)
{
// the operation succeeded and you got the number in num parameter
}
else
{
// the operation failed
}
string str = "123";
int i = Int.Parse(str);
If str is a valid integer string then it will be converted to integer and stored in i other wise Exception occur.
Starting with C# 7.0, you can declare the out variable in the argument
list of the method call, rather than in a separate variable
declaration. This produces more compact, readable code, and also
prevents you from inadvertently assigning a value to the variable
before the method call.
bool isDouble = double.TryParse(yourString, out double result);
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/out-parameter-modifier
You could use something like the following code:
string numbers = "numbers you want to check";
Regex regex = new Regex("^[0-9]+$"));
if (regex.IsMatch(numbers))
{
//string value is a number
}
public static void Main()
{
string id = "141241";
string id1 = "232a23";
string id2 = "12412a";
validation( id, id1, id2);
}
public static void validation(params object[] list)
{
string s = "";
int result;
string _Msg = "";
for (int i = 0; i < list.Length; i++)
{
s = (list[i].ToString());
if (string.IsNullOrEmpty(s))
{
_Msg = "Please Enter the value";
}
if (int.TryParse(s, out result))
{
_Msg = "Enter " + s.ToString() + ", value is Integer";
}
else
{
_Msg = "This is not Integer value ";
}
}
}
Try This
here i perform addition of no and concatenation of string
private void button1_Click(object sender, EventArgs e)
{
bool chk,chk1;
int chkq;
chk = int.TryParse(textBox1.Text, out chkq);
chk1 = int.TryParse(textBox2.Text, out chkq);
if (chk1 && chk)
{
double a = Convert.ToDouble(textBox1.Text);
double b = Convert.ToDouble(textBox2.Text);
double c = a + b;
textBox3.Text = Convert.ToString(c);
}
else
{
string f, d,s;
f = textBox1.Text;
d = textBox2.Text;
s = f + d;
textBox3.Text = s;
}
}
I'm not a programmer of particularly high skills, but when I needed to solve this, I chose what is probably a very non-elegant solution, but it suits my needs.
private bool IsValidNumber(string _checkString, string _checkType)
{
float _checkF;
int _checkI;
bool _result = false;
switch (_checkType)
{
case "int":
_result = int.TryParse(_checkString, out _checkI);
break;
case "float":
_result = Single.TryParse(_checkString, out _checkF);
break;
}
return _result;
}
I simply call this with something like:
if (IsValidNumber("1.2", "float")) etc...
It means that I can get a simple true/false answer back during If... Then comparisons, and that was the important factor for me. If I need to check for other types, then I add a variable, and a case statement as required.
use this
double num;
string candidate = "1";
if (double.TryParse(candidate, out num))
{
// It's a number!
}
int num;
bool isNumeric = int.TryParse("123", out num);
namespace Exception
{
class Program
{
static void Main(string[] args)
{
bool isNumeric;
int n;
do
{
Console.Write("Enter a number:");
isNumeric = int.TryParse(Console.ReadLine(), out n);
} while (isNumeric == false);
Console.WriteLine("Thanks for entering number" + n);
Console.Read();
}
}
}
Regex.IsMatch(stringToBeChecked, #"^\d+$")
Regex.IsMatch("141241", #"^\d+$") // True
Regex.IsMatch("232a23", #"^\d+$") // False
Regex.IsMatch("12412a", #"^\d+$") // False
The problem with some of the suggested solutions is that they don't take into account various float number formats. The following function does it:
public bool IsNumber(String value)
{
double d;
if (string.IsNullOrWhiteSpace(value))
return false;
else
return double.TryParse(value.Trim(), System.Globalization.NumberStyles.Any,
System.Globalization.CultureInfo.InvariantCulture, out d);
}
It assumes that the various float number styles such es decimal point (English) and decima comma (German) are all allowed. If that is not the case, change the number styles paramater. Note that Any does not include hex mumbers, because the type double does not support it.
What is the main difference between int.Parse() and Convert.ToInt32()?
Which one is to be preferred
If you've got a string, and you expect it to always be an integer (say, if some web service is handing you an integer in string format), you'd use Int32.Parse().
If you're collecting input from a user, you'd generally use Int32.TryParse(), since it allows you more fine-grained control over the situation when the user enters invalid input.
Convert.ToInt32() takes an object as its argument. (See Chris S's answer for how it works)
Convert.ToInt32() also does not throw ArgumentNullException when its argument is null the way Int32.Parse() does. That also means that Convert.ToInt32() is probably a wee bit slower than Int32.Parse(), though in practice, unless you're doing a very large number of iterations in a loop, you'll never notice it.
Have a look in reflector:
int.Parse("32"):
public static int Parse(string s)
{
return System.Number.ParseInt32(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo);
}
which is a call to:
internal static unsafe int ParseInt32(string s, NumberStyles style, NumberFormatInfo info)
{
byte* stackBuffer = stackalloc byte[1 * 0x72];
NumberBuffer number = new NumberBuffer(stackBuffer);
int num = 0;
StringToNumber(s, style, ref number, info, false);
if ((style & NumberStyles.AllowHexSpecifier) != NumberStyles.None)
{
if (!HexNumberToInt32(ref number, ref num))
{
throw new OverflowException(Environment.GetResourceString("Overflow_Int32"));
}
return num;
}
if (!NumberToInt32(ref number, ref num))
{
throw new OverflowException(Environment.GetResourceString("Overflow_Int32"));
}
return num;
}
Convert.ToInt32("32"):
public static int ToInt32(string value)
{
if (value == null)
{
return 0;
}
return int.Parse(value, CultureInfo.CurrentCulture);
}
As the first (Dave M's) comment says.
No difference as such.
Convert.ToInt32() calls int.Parse() internally
Except for one thing Convert.ToInt32() returns 0 when argument is null
Otherwise both work the same way
int.Parse(string s)
Integer in RANGE > returns integer value
Null value > ArguementNullException
Not in format > FormatException
Value not in RANGE > OverflowException
Convert.ToInt32(string s)
Integer in RANGE > returns integer value
Null value > returns "0"
Not in format > FormatException
Value not in RANGE > OverflowException
bool isParsed = int.TryParse(string s,out res)
Integer in RANGE > returns integer value, isParsed = true
Null value > returns "0", isParsed = false
Not in format > returns "0", isParsed = false
Value not in RANGE > returns "0", isParsed = false
Try this code below.....
class Program
{
static void Main(string[] args)
{
string strInt = "24532";
string strNull = null;
string strWrongFrmt = "5.87";
string strAboveRange = "98765432123456";
int res;
try
{
// int.Parse() - TEST
res = int.Parse(strInt); // res = 24532
res = int.Parse(strNull); // System.ArgumentNullException
res = int.Parse(strWrongFrmt); // System.FormatException
res = int.Parse(strAboveRange); // System.OverflowException
// Convert.ToInt32(string s) - TEST
res = Convert.ToInt32(strInt); // res = 24532
res = Convert.ToInt32(strNull); // res = 0
res = Convert.ToInt32(strWrongFrmt); // System.FormatException
res = Convert.ToInt32(strAboveRange); //System.OverflowException
// int.TryParse(string s, out res) - Test
bool isParsed;
isParsed = int.TryParse(strInt, out res); // isParsed = true, res = 24532
isParsed = int.TryParse(strNull, out res); // isParsed = false, res = 0
isParsed = int.TryParse(strWrongFrmt, out res); // isParsed = false, res = 0
isParsed = int.TryParse(strAboveRange, out res); // isParsed = false, res = 0
}
catch(Exception e)
{
Console.WriteLine("Check this.\n" + e.Message);
}
}
The difference is this:
Int32.Parse() and Int32.TryParse() can only convert strings. Convert.ToInt32() can take any class that implements IConvertible. If you pass it a string, then they are equivalent, except that you get extra overhead for type comparisons, etc. If you are converting strings, then TryParse() is probably the better option.
Int32.parse(string)--->
Int32.Parse (string s) method converts the string representation of a number to its 32-bit signed integer equivalent. When s is a null reference, it will throw ArgumentNullException. If s is other than integer value, it will throw FormatException. When s represents a number less than MinValue or greater than MaxValue, it will throw OverflowException. For example:
string s1 = "1234";
string s2 = "1234.65";
string s3 = null;
string s4 = "123456789123456789123456789123456789123456789";
result = Int32.Parse(s1); //1234
result = Int32.Parse(s2); //FormatException
result = Int32.Parse(s3); //ArgumentNullException
result = Int32.Parse(s4); //OverflowException
Convert.ToInt32(string) -->
Convert.ToInt32(string s) method converts the specified string representation of 32-bit signed integer equivalent. This calls in turn Int32.Parse () method. When s is a null reference, it will return 0 rather than throw ArgumentNullException. If s is other than integer value, it will throw FormatException. When s represents a number less than MinValue or greater than MaxValue, it will throw OverflowException.
For example:
result = Convert.ToInt32(s1); // 1234
result = Convert.ToInt32(s2); // FormatException
result = Convert.ToInt32(s3); // 0
result = Convert.ToInt32(s4); // OverflowException
TryParse is faster...
The first of these functions, Parse, is one that should be familiar to
any .Net developer. This function will take a string and attempt to
extract an integer out of it and then return the integer. If it runs
into something that it can’t parse then it throws a FormatException or
if the number is too large an OverflowException. Also, it can throw an
ArgumentException if you pass it a null value.
TryParse is a new addition to the new .Net 2.0 framework that addresses some issues with the original Parse function. The main
difference is that exception handling is very slow, so if TryParse is
unable to parse the string it does not throw an exception like Parse
does. Instead, it returns a Boolean indicating if it was able to
successfully parse a number. So you have to pass into TryParse both
the string to be parsed and an Int32 out parameter to fill in. We will
use the profiler to examine the speed difference between TryParse and
Parse in both cases where the string can be correctly parsed and in
cases where the string cannot be correctly parsed.
The Convert class contains a series of functions to convert one base class into another. I believe that
Convert.ToInt32(string) just checks for a null string (if the string
is null it returns zero unlike the Parse) then just calls
Int32.Parse(string). I’ll use the profiler to confirm this and to see
if using Convert as opposed to Parse has any real effect on
performance.
Source with examples
Hope this helps.
Convert.ToInt32
has 19 overloads or 19 different ways that you can call it. Maybe more in 2010 versions.
It will attempt to convert from the following TYPES;
Object, Boolean, Char, SByte, Byte, Int16, UInt16, Int32, UInt32, Int64, UInt64, Single, Double, Decimal, String, Date
and it also has a number of other methods; one to do with a number base and 2 methods involve a System.IFormatProvider
Parse on the other hand only has 4 overloads or 4 different ways you can call the method.
Integer.Parse( s As String)
Integer.Parse( s As String, style As System.Globalization.NumberStyles )
Integer.Parse( s As String, provider As System.IFormatProvider )
Integer.Parse( s As String, style As System.Globalization.NumberStyles, provider As System.IFormatProvider )
Here is a detail for int.Parse and Convert.ToInt32:
Say, you have a char array, char[] a=['1','2','3','4'] and want to convert each element into an integer.
The Convert.ToInt32(a[0]) will give you a number of 49. It treats it as ASCII code
The int.Parse(a[0]) will give you the right output which is 1
If you have a string array string[] b=['1','2','3','4'], then Convert.ToInt32 and int.Parse will have no difference in output. Both return the right integer.
Convert.ToInt32 allows null value, it doesn't throw any errors
Int.parse does not allow null value, it throws an ArgumentNullException error.
It depends on the parameter type. For example, I just discovered today that it will convert a char directly to int using its ASCII value. Not exactly the functionality I intended...
YOU HAVE BEEN WARNED!
public static int ToInt32(char value)
{
return (int)value;
}
Convert.ToInt32('1'); // Returns 49
int.Parse('1'); // Returns 1
Parse() methods provide the number styles which cannot be used for Convert(). For example:
int i;
bool b = int.TryParse( "123-",
System.Globalization.NumberStyles.AllowTrailingSign,
System.Globalization.CultureInfo.InvariantCulture,
out i);
would parse the numbers with trailing sign so that i == -123
The trailing sign is popular in ERP systems.
for clarification open console application, just copy below code and paste it in static void Main(string[] args) method, I hope you can understand
public class Program
{
static void Main(string[] args)
{
int result;
bool status;
string s1 = "12345";
Console.WriteLine("input1:12345");
string s2 = "1234.45";
Console.WriteLine("input2:1234.45");
string s3 = null;
Console.WriteLine("input3:null");
string s4 = "1234567899012345677890123456789012345667890";
Console.WriteLine("input4:1234567899012345677890123456789012345667890");
string s5 = string.Empty;
Console.WriteLine("input5:String.Empty");
Console.WriteLine();
Console.WriteLine("--------Int.Parse Methods Outputs-------------");
try
{
result = int.Parse(s1);
Console.WriteLine("OutPut1:" + result);
}
catch (Exception ee)
{
Console.WriteLine("OutPut1:"+ee.Message);
}
try
{
result = int.Parse(s2);
Console.WriteLine("OutPut2:" + result);
}
catch (Exception ee)
{
Console.WriteLine("OutPut2:" + ee.Message);
}
try
{
result = int.Parse(s3);
Console.WriteLine("OutPut3:" + result);
}
catch (Exception ee)
{
Console.WriteLine("OutPut3:" + ee.Message);
}
try
{
result = int.Parse(s4);
Console.WriteLine("OutPut4:" + result);
}
catch (Exception ee)
{
Console.WriteLine("OutPut4:" + ee.Message);
}
try
{
result = int.Parse(s5);
Console.WriteLine("OutPut5:" + result);
}
catch (Exception ee)
{
Console.WriteLine("OutPut5:" + ee.Message);
}
Console.WriteLine();
Console.WriteLine("--------Convert.To.Int32 Method Outputs-------------");
try
{
result= Convert.ToInt32(s1);
Console.WriteLine("OutPut1:" + result);
}
catch (Exception ee)
{
Console.WriteLine("OutPut1:" + ee.Message);
}
try
{
result = Convert.ToInt32(s2);
Console.WriteLine("OutPut2:" + result);
}
catch (Exception ee)
{
Console.WriteLine("OutPut2:" + ee.Message);
}
try
{
result = Convert.ToInt32(s3);
Console.WriteLine("OutPut3:" + result);
}
catch (Exception ee)
{
Console.WriteLine("OutPut3:" + ee.Message);
}
try
{
result = Convert.ToInt32(s4);
Console.WriteLine("OutPut4:" + result);
}
catch (Exception ee)
{
Console.WriteLine("OutPut4:" + ee.Message);
}
try
{
result = Convert.ToInt32(s5);
Console.WriteLine("OutPut5:" + result);
}
catch (Exception ee)
{
Console.WriteLine("OutPut5:" + ee.Message);
}
Console.WriteLine();
Console.WriteLine("--------TryParse Methods Outputs-------------");
try
{
status = int.TryParse(s1, out result);
Console.WriteLine("OutPut1:" + result);
}
catch (Exception ee)
{
Console.WriteLine("OutPut1:" + ee.Message);
}
try
{
status = int.TryParse(s2, out result);
Console.WriteLine("OutPut2:" + result);
}
catch (Exception ee)
{
Console.WriteLine("OutPut2:" + ee.Message);
}
try
{
status = int.TryParse(s3, out result);
Console.WriteLine("OutPut3:" + result);
}
catch (Exception ee)
{
Console.WriteLine("OutPut3:" + ee.Message);
}
try
{
status = int.TryParse(s4, out result);
Console.WriteLine("OutPut4:" + result);
}
catch (Exception ee)
{
Console.WriteLine("OutPut4:" + ee.Message);
}
try
{
status = int.TryParse(s5, out result);
Console.WriteLine("OutPut5:" + result);
}
catch (Exception ee)
{
Console.WriteLine("OutPut5:" + ee.Message);
}
Console.Read();
}
}