Swiftorial Logo
Home
Swift Lessons
AI Tools
Learn More
Career
Resources

Type Conversion in C#

Introduction

Type conversion in C# refers to changing a variable from one data type to another. It is a common operation that often needs to be performed in programming to ensure data is in the correct format. There are two types of type conversions in C#: Implicit and Explicit.

Implicit Conversion

Implicit conversions are performed by the C# compiler automatically when there is no risk of data loss. For example, converting a smaller data type to a larger data type.

Example:

int num = 123;
double d = num;
Console.WriteLine(d); // Output: 123
123

Explicit Conversion

Explicit conversions require a cast operator because there is a possibility of data loss. This is also known as casting.

Example:

double d = 123.45;
int num = (int)d;
Console.WriteLine(num); // Output: 123
123

Using Convert Class

The Convert class provides methods to convert between different data types in a more controlled manner.

Example:

string str = "123";
int num = Convert.ToInt32(str);
Console.WriteLine(num); // Output: 123
123

Parse and TryParse Methods

The Parse and TryParse methods are used to convert strings to other data types. TryParse is safer as it does not throw an exception if the conversion fails.

Example using Parse:

string str = "123";
int num = int.Parse(str);
Console.WriteLine(num); // Output: 123
123

Example using TryParse:

string str = "123";
int num;
bool result = int.TryParse(str, out num);
Console.WriteLine(result); // Output: True
Console.WriteLine(num); // Output: 123
True
123

Custom Type Conversion

Custom type conversion can be achieved by overriding the ToString method or by implementing the IConvertible interface in your custom classes.

Example:

public class Person
{
  public string Name { get; set; }
  public override string ToString()
  {
    return Name;
  }
}

Person person = new Person { Name = "John" };
string personString = person.ToString();
Console.WriteLine(personString); // Output: John
John

Conclusion

Understanding type conversion is essential for effective C# programming. Whether using implicit, explicit, or custom conversions, knowing how and when to convert types can help prevent errors and ensure data integrity.