Type Conversion in C#

Type Conversion in C#

The process of converting one type to another is called type conversion. In C#, you can perform the following kinds of conversions:

  • Implicit conversions
  • Explicit conversions
  • User-defined conversions
  • Conversion with a helper class

To go more in detail about Implicit and Explicit conversions read my previous article Boxing and Unboxing in C#

Implicit conversions

An implicit conversion doesn’t need any special syntax, it can be executed because the compiler knows that the conversion is allowed and that it’s safe to convert.

A value type such as int can be stored as a double because an int can fit inside a double without losing any precision or from a reference type to one of its base types.

In this example num is int and will be converted to double and no data will be lost.

int num = 123456;
double bigNum = num;
Console.WriteLine("bigNum: {0}", bigNum); 
/* Output:
    bigNum: 123456
*/
        

Also for reference types, no special syntax is necessary because a derived class always contains all the members of a base class. In these cases, the cast is done implicitly by the compiler.

Rectangle rectangle = new Rectangle();
Shape shape = rectangle;
        

Explicit conversions

Because of the type safety of the C# language, the compiler protects you from all implicit conversions that are not safe, such as converting a double to an int. If you do want to make this conversion, you need to do it explicitly. This is called casting.

To perform a cast, specify the type that you are casting to in parentheses in front of the value or variable to be converted.

In this example bigNum is double and will be converted to int and decimal data will be lost.

double bigNum = 123456.789;
int num = (int)bigNum;
Console.WriteLine("num: {0}",num);
/* Output: 
    num: 123456 
*/
        

For reference types, an explicit cast is required if you need to convert from a base type to a derived type.

Rectangle rectangle = new Rectangle();
Shape shape = rectangle;
Rectangle rectangle2 = (Rectangle)shape;
        

User-defined conversions

When creating your own types, you can add support for both implicit and explicit conversions.

User-defined conversions are performed by special methods that you can define to enable explicit and implicit conversions between custom types that do not have a base class–derived class relationship.

For User-defined conversion we use Conversion Operators:

  • With implicit conversions occur automatically when it is required.
  • With explicit conversions require a cast to be called.
  • All User-defined conversions must be declared as static.

In this example, we have an explicit conversion in Minute class to easily cast Minute to Second.

public static explicit operator Second(Minute minutes)
{
    return new Second(minutes * 60);
}
        

Conversion with a helper class

For converting between non compatible types, you can use System.BitConverter. For conversion between compatible types, you can use System.Convert and the Parse or TryParse methods on various types.

In this example, we convert int type to string using System.Convert.

int num = 123;
string numText = Convert.ToString(num);
Console.WriteLine("numText: {0}",numText); 
/* Output: 
    numText: "123" 
*/        

Feel free to explore more of my articles on my blog www.ottorinobruni.com for additional insights. Your feedback and comments are always welcome!

To view or add a comment, sign in

More articles by Ottorino B.

  • What is Microsoft Blazor framework?

    What is Microsoft Blazor framework? Introduction As a fullstack Microsoft developer, my professional journey has…

  • How to Modify Variable Values in Xcode Debugger

    Let’s face it, having a bunch of solid tests is usually the best way to keep your code in check. But, there are those…

  • How to develop MAUI app with VS Code

    Introduction Towards the end of the summer, Microsoft made the decision to retire a software that I use daily at home:…

  • Review of NDepend: A Swiss army knife for .NET developers

    Some time ago, I had the privilege of being contacted by Patrick Smacchia, CEO and lead developer at NDepend to try out…

  • Dependency Inversion Principle (DIP) in C#

    In my previous articles I wrote about Solid Principles in C#. In this article, I am going to show you when and how to…

  • Interface Segregation Principle (ISP) in C#

    In my previous articles I wrote about Solid Principles in C#. In this article, I am going to show you when and how to…

  • Liskov Substitution Principle (LSP) in C#

    In my previous articles I wrote about Solid Principles in C#. In this article, I am going to show you when and how to…

  • Open Closed Principle (OCP) in C#

    In my previous articles I wrote about Solid Principles in C# and the Single Responsibility Principle. In this article…

    1 Comment
  • Single Responsibility Principle (SRP) in C#

    In my previous article I wrote about what they are and why to use Solid Principles in C#. In this article, I am going…

  • Solid Principles in C# - Introduction

    It's time to talk about a topic that every developer should know to work better regardless of the language or framework…

Explore content categories