From C# basics This is the most frequently asked interview question it anytime. So let’s try to understand using simple example. To answer this in a sort way, the int.Parse() and int.TryPrase() methods is used to convert a string representation of number to an integer.
In case if our given string can not be converted in int format then int.Parse() produce or throws an Exception where as int.TryParse() returns a boolean result which is false
int.Parse()
int.Parse is used for Convert a string representation of number to an integer.
string str = "55";
int i = int.Parse(str);
This will execute perfect by using int.Parse() and gives 55 as int in output. So in case if there is any bad format string then int.Parse() throws 3 different types of exeptions which are :
1. ) If parameter value is null, then it will throw ArgumentNullException
Ex :-
string str = null ;
int i = int.Parse(str);
2. ) If parameter value is other than integer value or not in proper format,it will throw FormatException.
Ex :-
string str = "55.12121";
int i = int.Parse(str)
3. ) If parameter value is out of integer ranges, then it will throw OverflowException.
Ex :-
string str = "5532423421111112222211";
int i = int.Parse(str)
int.TryParse()
Incase of int.TryParse() method, when it converts the string representation of an number to an integer; it set the the out variable with the result integer and returns true if successfully parsed, otherwise false.
string str = "5555";
int result ;
bool isDone = int.TryParse(str , out result);
Output ==>> result = 100 and isDone = true
Case of exception
string str = "5555.23232";
int result ;
bool isDone = int.TryParse(str , out result);
Output ==>> result = 0 and isDone = false
.
0 comments:
Post a Comment