Conversions in C#
1.Implicit
=>Small to Big
=> InBuilt Automatically will Do
Ex:
int numInt = 10;
long numLong = numInt; // Implicit conversion from int to long
2.Explicit (Casting)
=>Big to Small
Ex:
double numDouble = 3.14159;
int numInt = (int)numDouble; // Explicit conversion from double to int (data loss)
3.Convert Class:
=>The Convert class in C# provides methods for converting between different base data types, such as numbers and strings.
string strNum = "123";
int num = Convert.ToInt32(strNum); // String to int conversion
4.Parsing:
=>For converting from strings to other data types, you can use the Parse methods provided by various data types (like int.Parse, double.Parse, etc.).
Ex:
string strDouble = "3.14";
double numDouble = double.Parse(strDouble); // String to double conversion
5.TryParse:
=> To handle potential parsing errors without throwing exceptions, you can use the TryParse methods, which return a boolean indicating the success of the conversion and store the result in an out parameter.
Ex:
string strInt = "123";
int parsedInt;
bool success = int.TryParse(strInt, out parsedInt);
if (success)
{
// Conversion successful
}
6.Convert.ChangeType:
=>The Convert.ChangeType method allows you to convert an object to a specified type at runtime.
Ex:
object obj = 5;
int num = (int)Convert.ChangeType(obj, typeof(int)); // Runtime conversion
Comments
Post a Comment