Learn to enhance your C# code’s performance and readability by avoiding exceptions for flow control. Discover a better approach using TryParse on Day 24 of our 30-Day .NET Challenge.
Introduction
Exceptions are designed to handle unexpected situations rather than controlling the application flow. Using exceptions during input validation can affect your application's readability and performance.
Learning Objectives
The inefficient use of exceptions
A better approach using TryParse
Prerequisites for Developers
- Basic understanding of C# programming language.
Getting Started
The inefficient use of exceptions
Using exceptions for flow control, especially in a loop or frequently called code, may lead to severe performance bottlenecks. It also makes code hard to understand.
Exceptions are really expensive in terms of system resources because when an exception is triggered, .Net runtime captures the stack trace and the process is resource-intensive.
try
{
int.Parse(input); // Attempt to parse input
}
catch (FormatException)
{
// Handle the invalid input
}
A better approach using TryParse
Please find below the refactored version of the previous code snippet
if (int.TryParse(input, out int result))
{
// Use the parsed value
}
else
{
// Handle the invalid input
}
The aforementioned code attempts to parse the input supplied from the console and returns a boolean whether it's a success or failure.
Complete Code
Create another class named AvoidExceptions and add the following code snippet
public static class AvoidExceptions
{
public static void BadWay(string input)
{
// Inefficient way: Using exceptions for flow control
try
{
int number = int.Parse(input);
Console.WriteLine($"You entered (Exception method): {number}");
}
catch (FormatException)
{
Console.WriteLine("Invalid input! Please enter a valid integer.");
}
}
public static void GoodWay(string input)
{
// Efficient way: Using TryParse for flow control
if (int.TryParse(input, out int result))
{
Console.WriteLine($"You entered (TryParse method): {result}");
}
else
{
Console.WriteLine("Invalid input! Please enter a valid integer.");
}
}
}
Execute from the main method as follows
#region Day 24: Avoid Exceptions in Flow Control
static string ExecuteDay24()
{
Console.WriteLine("Enter a number:");
string input = Console.ReadLine();
AvoidExceptions.BadWay(input);
AvoidExceptions.GoodWay(input);
return "Executed Day 24 successfully..!!";
}
#endregion
Console Output
Invalid input! Please enter a valid integer.
Invalid input! Please enter a valid integer.
Complete Code on GitHub
GitHub — ssukhpinder/30DayChallenge.Net
C# Programming🚀
Thank you for being a part of the C# community! Before you leave:
Follow us: Youtube | X | LinkedIn | Dev.to
Visit our other platforms: GitHub
More content at C# Programming