C# Tutorial

C# String

C# Array

C# Flow Control

C# Class and Object

C# Inheritance

C# Interface

C# Collection

C# Generic

C# File I/O

C# Delegate and Event

C# Exception

C# Process and Thread

C# ADO.NET Database Operations

C# Type Conversion

In C#, you may need to convert a value from one data type to another. This is known as type conversion. There are two types of type conversion: implicit and explicit.

  • Implicit type conversion

Implicit type conversion, also known as type coercion, is when the compiler automatically converts one data type to another without the programmer explicitly requesting the conversion. This typically occurs when converting a smaller data type to a larger one, or when there is no risk of data loss.

int num = 42;
double dbl = num; // Implicit conversion from int to double

Console.WriteLine(dbl); // Output: 42
  • Explicit type conversion

Explicit type conversion, also known as casting, is when the programmer explicitly requests a conversion between incompatible data types. This is typically required when converting a larger data type to a smaller one, or when there is a risk of data loss or truncation.

double dbl = 42.5;
int num = (int)dbl; // Explicit conversion (casting) from double to int

Console.WriteLine(num); // Output: 42 (decimal part is truncated)
  • Using Convert class

The Convert class provides methods for converting between different data types, including numeric, Boolean, and character types. The Convert class is part of the System namespace.

string strNum = "123";
int num = Convert.ToInt32(strNum);

Console.WriteLine(num); // Output: 123
  • Using Parse and TryParse methods

Numeric types, such as int, float, double, and decimal, provide Parse and TryParse methods for converting a string representation of a number to the corresponding numeric type.

string strNum = "123";
int num = int.Parse(strNum);

Console.WriteLine(num); // Output: 123

The TryParse method returns a Boolean value indicating whether the conversion was successful and uses an out parameter to store the converted value.

string strNum = "123";
int num;

if (int.TryParse(strNum, out num))
{
    Console.WriteLine(num); // Output: 123
}
else
{
    Console.WriteLine("Invalid number");
}

In this tutorial, we covered the basics of type conversion in C#. Type conversion is necessary when you need to convert a value from one data type to another. Implicit type conversion occurs automatically when there is no risk of data loss, while explicit type conversion requires casting. The Convert class provides methods for converting between different data types, and numeric types offer Parse and TryParse methods for converting a string representation of a number to the corresponding numeric type.

  1. How to perform type conversion in C#

    Type conversion, also known as casting, is the process of converting one type of data into another type. It can be performed implicitly or explicitly, depending on the compatibility of the types.

    using System;
    
    class Program
    {
        static void Main()
        {
            // Implicit type conversion
            int intValue = 42;
            double doubleValue = intValue;
    
            Console.WriteLine("Implicit Conversion: " + doubleValue);
    
            // Explicit type conversion (casting)
            double anotherDoubleValue = 56.78;
            int anotherIntValue = (int)anotherDoubleValue;
    
            Console.WriteLine("Explicit Conversion: " + anotherIntValue);
        }
    }
    
  2. Implicit vs. explicit type conversion in C#

    Implicit type conversion is done automatically by the compiler when there is no loss of data. Explicit type conversion (casting) requires the programmer to specify the conversion and may result in data loss.

    using System;
    
    class Program
    {
        static void Main()
        {
            // Implicit conversion
            int intValue = 42;
            double doubleValue = intValue;
    
            Console.WriteLine("Implicit Conversion: " + doubleValue);
    
            // Explicit conversion (casting) with data loss
            double anotherDoubleValue = 56.78;
            int anotherIntValue = (int)anotherDoubleValue;
    
            Console.WriteLine("Explicit Conversion: " + anotherIntValue);
        }
    }
    
  3. Casting in C#

    Casting is the explicit conversion of one data type to another. It is performed using parentheses and the target type.

    using System;
    
    class Program
    {
        static void Main()
        {
            double doubleValue = 56.78;
            int intValue = (int)doubleValue;
    
            Console.WriteLine("Casting: " + intValue);
        }
    }
    
  4. Type conversion between primitive types in C#

    using System;
    
    class Program
    {
        static void Main()
        {
            // Type conversion between primitive types
            int intValue = 42;
            double doubleValue = Convert.ToDouble(intValue);
    
            Console.WriteLine("Type Conversion: " + doubleValue);
        }
    }
    
  5. C# Convert class and type conversion

    The Convert class in C# provides methods for converting one type to another. It is commonly used for converting between primitive types.

    using System;
    
    class Program
    {
        static void Main()
        {
            string stringValue = "123";
            int intValue = Convert.ToInt32(stringValue);
    
            Console.WriteLine("Converted Int Value: " + intValue);
        }
    }
    
  6. String to int conversion in C#

    using System;
    
    class Program
    {
        static void Main()
        {
            // String to int conversion
            string stringValue = "123";
            int intValue = int.Parse(stringValue);
    
            Console.WriteLine("String to Int Conversion: " + intValue);
        }
    }
    
  7. Numeric type conversion in C#

    using System;
    
    class Program
    {
        static void Main()
        {
            // Numeric type conversion
            double doubleValue = 56.78;
            int intValue = (int)doubleValue;
    
            Console.WriteLine("Numeric Type Conversion: " + intValue);
        }
    }
    
  8. Type conversion with Parse and TryParse methods in C#

    using System;
    
    class Program
    {
        static void Main()
        {
            // Using Parse method
            string stringValue = "123";
            int intValue = int.Parse(stringValue);
    
            Console.WriteLine("Parse Method: " + intValue);
    
            // Using TryParse method
            string invalidStringValue = "abc";
            int result;
            bool success = int.TryParse(invalidStringValue, out result);
    
            if (success)
                Console.WriteLine("TryParse Method: " + result);
            else
                Console.WriteLine("Invalid value for conversion.");
        }
    }
    
  9. Custom type conversion operators in C#

    using System;
    
    class Distance
    {
        public int Feet { get; set; }
    
        // Custom type conversion operator
        public static implicit operator int(Distance d)
        {
            return d.Feet;
        }
    }
    
    class Program
    {
        static void Main()
        {
            Distance distance = new Distance { Feet = 5 };
            int feetValue = distance; // Implicit type conversion
    
            Console.WriteLine("Feet Value: " + feetValue);
        }
    }
    
  10. Handling conversion errors in C#

    using System;
    
    class Program
    {
        static void Main()
        {
            // Handling conversion errors with Try-Catch
            string invalidStringValue = "abc";
    
            try
            {
                int intValue = int.Parse(invalidStringValue);
                Console.WriteLine("Converted Int Value: " + intValue);
            }
            catch (FormatException)
            {
                Console.WriteLine("Invalid value for conversion.");
            }
        }
    }
    
  11. User-defined type conversion in C#

    using System;
    
    class Distance
    {
        public int Feet { get; set; }
    
        public Distance(int feet)
        {
            Feet = feet;
        }
    
        // User-defined type conversion method
        public static implicit operator Distance(int feet)
        {
            return new Distance(feet);
        }
    }
    
    class Program
    {
        static void Main()
        {
            Distance distance = 5; // User-defined type conversion
            Console.WriteLine("Feet Value: " + distance.Feet);
        }
    }
    
  12. Type conversion in LINQ queries in C#

    using System;
    using System.Collections.Generic;
    using System.Linq;
    
    class Program
    {
        static void Main()
        {
            // Type conversion in LINQ query
            List<string> stringList = new List<string> { "1", "2", "3" };
            List<int> intList = stringList.Select(s => int.Parse(s)).ToList();
    
            Console.WriteLine("Converted Int List: " + string.Join(", ", intList));
        }
    }