Parsing and converting

Entity integrity and domain integrity involve allowing valid values into our application for further processing. Valid values include manipulating or managing input provided by a user, rendering it as data that is acceptable to the application. This process may including parsing specific types of data to the type our application accepts, converting data types, and so on. 

Parse and TryParse are two statements available across multiple data types within the .NET Framework, for example if you are writing a console application and you want to accept parameters as command-line arguments. In a console application, command-line parameters are always of the string type. So, how do you parse these arguments from the string type to another required type?

In the following example, we know that our first parameter is a Boolean value, but is passed as a string. When we are certain of the value passed, we can use the parse method to convert the string to a Boolean. Parse compares to with static string values and returns either true or false. When invalid data is passed, an exception is thrown—Input string is in an invalid format.

Let's start with an example. Define two methods that each take a parameter of the string type. We want to parse it into Boolean and integer values. Parsing a Boolean is as simple as using the parse method of a Boolean type. However, for the integer type, there are two approaches. One is to use parse, as we did when parsing a Boolean, and the other is TryParse. When we are not sure if the string parameter provided is an integer or not, then we can use the TryParse method, which will then give us a bool result on which we can set up our logic. In the following example, we are showing both ways. This will allow us to handle exceptions and provide the user with a meaningful message:

internal class ParseSamples
{
internal void ProcessBool(string boolValue)
{
if (bool.Parse(boolValue))
{
Console.WriteLine($"Parsed bool value is :
{bool.Parse(boolValue)}");
}
}

internal void ProcessInteger(string intValue)
{

int processedValue =int.MinValue;
if (int.TryParse(intValue, out processedValue))
{
Console.WriteLine($"Parsed int value is :
{processedValue}");
}
else
{
Console.WriteLine("Parsed value is not an integer");
}
Console.WriteLine($"Parsed int value is :
{int.Parse(intValue)}");

Now that our sample class is ready, let's invoke it using our main method. Here, we have a switch statement to check the length of the arguments passed to the main method. If it is 1, call the processbool method; if it is 2, call both methods, otherwise, a message is displayed:

 static void Main(string[] args)
{
ParseSamples ps = new ParseSamples();
switch (args.Length)
{
case 1:
ps.ProcessBools(args[0]);
break;
case 2:
ps.ProcessBools(args[0]);
ps.ProcessIntegers(args[1]);
break;
default:
Console.WriteLine("Please provide one or two
command line arguments");
break;
}


// Keep the console window open in debug mode.
System.Console.WriteLine("Press any key to exit.");
System.Console.ReadKey();
}

To invoke this method, because we are trying to read command-line arguments in our program, these need to be passed at runtime or from the Properties window, which will then be read at runtime. Parameters are passed from the Properties window as follows. Right-click on Project, select Properties, and then navigate to the Debug tab, where you can set these parameters:

When you run the program, as you pass 1 or 2 arguments, the respective case statements get executed and the output will be presented on the screen:

//Command line argument true
Parsed bool value is : True
Press any key to exit.

//Command line argument true 11
Parsed bool value is : True
Parsed int value is : 11
Parsed int value is : 11
Press any key to exit.

//Command line arguments true Madhav
Parsed bool value is : True
Parsed value is not an integer

Here, in the last output, TryParse statements are processed, but Parse will throw an error as follows. Because Parse expects a proper string to be passed, when a non-string value is passed, or when your statement doesn't correspond to the value passed, it throws an error. However, if we handle this statement using try..catch, we won't see any issues. Otherwise, your program will break and an exception dialog will appear as follows: 

Another way to validate your input is to use the conversion method. Convert is a method defined in .NET Framework that casts a base type to another base type. Unlike Parse, Convert accepts an object of a type and converts it into another type. Parse accepts only string input. Also, when a null value is passed, Convert returns the minimum value of the target type. The Convert class has a few static methods that support conversion to and from different types in .NET Framework. Types supported by the Convert method are Boolean, Char, SByte, Byte, Int16, Int32, Int64, UInt16, UInt32, UInt64, Single, Double, Decimal, DateTime, and String

When you apply the Convert method, you can expect any of the following output. The system either successfully converts the source type to the target type or throws one of the following exceptions: FormatException, InvalidCastException, or ArgumentNull. Let's look at an example:

internal void ConvertSample()
{
try
{
string svalue =string.Empty;
Console.WriteLine(Convert.ToInt32(svalue));
}
catch (FormatException fx)
{
Console.WriteLine("Format Exception : "+fx.Message);
}
try
{
double dvalue = 1212121212121212.12;
Console.WriteLine(Convert.ToInt32(dvalue));
}
catch (OverflowException ox)
{
Console.WriteLine("OverFlow Exception : " + ox.Message);
}
try
{
DateTime date= DateTime.Now;
Console.WriteLine(Convert.ToDouble(date));
}
catch (InvalidCastException ix)
{
Console.WriteLine("Invalid cast Exception : " + ix.Message);
}
double dvalue1 = 12.22;
Console.WriteLine("Converted Value : " + Convert.ToInt32(dvalue1));
}

In the preceding example, we tried to convert different types. The important thing to note is that you can get any output while converting, and so you have to handle it accordingly in your application code. Also, while converting decimal or float values to integers, precise information is lost. However, no exception is thrown.

With same-type conversions, there won't be any exceptions or conversions. FormatException is thrown when you try to convert a string to any other type. String to Boolean, String to Char, or String to DateTime may throw this exception.

InvalidCastException occurs when a conversion between specific types is not valid, as in the following examples:

  • Conversions from Char to Boolean, Single, Double, Decimal, or DateTime
  • Conversions from Boolean, Single, Double, Decimal, or DateTime to Char
  • Conversions from DateTime to any other type except String
  • Conversions from any other type, except String, to DateTime

OverflowException is thrown in the event of loss of data, for example, when converting a huge decimal to an integer, as shown in our example. In our example, we are converting a double value to an int value. The int type variable in C# has a minimum and maximum value. If the number passed is outside this range, an overflow exception is raised:

Format Exception : Input string was not in a correct format.
OverFlow Exception : Value was either too large or too small for an Int32.
Invalid cast Exception : Invalid cast from 'DateTime' to 'Double'.
Converted Value : 12
Press any key to exit.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.217.211.92