Convert & Parse methods
There are two groups of methods, which aid us at converting values.
using System;
class CSharpApp
{
static void Main()
{
Console.WriteLine(Convert.ToBoolean(0.3));
Console.WriteLine(Convert.ToBoolean(3));
Console.WriteLine(Convert.ToBoolean(0));
Console.WriteLine(Convert.ToBoolean(-1));
Console.WriteLine(Convert.ToInt32("452"));
Console.WriteLine(Convert.ToInt32(34.5));
}
}
The
Convert class has many methods for converting values.
We use two of them.
Console.WriteLine(Convert.ToBoolean(0.3));
We convert a
double value to a
bool value.
Console.WriteLine(Convert.ToInt32("452"));
And here we convert a
string to
int.
using System;
class CSharpApp
{
static void Main()
{
Console.WriteLine(Int32.Parse("34"));
Console.WriteLine(Int32.Parse("-34"));
Console.WriteLine(Int32.Parse("+34"));
}
}
Converting strings to integers is a very common task. Often when
we bring values from databases or GUI widgets.
Console.WriteLine(Int32.Parse("34"));
We use the
Parse() method of the
Int32 class
to convert a
string to
int value.
No comments:
Post a Comment