Skip to main content

Understanding Type Casting or Type Conversion in C#

Type Casting or Type Conversion is a mechanism to convert one data type value to another one. Type conversion is possible if both the data types are compatible to each other; otherwise you will get an InvalidCastException.

Different Types of Type Casting or Type Conversion

  1. Implicit conversion

    Implicit conversion is being done automatically by the compiler and no data will be lost. It includes conversion of a smaller data type to a larger data types and conversion of derived classes to base class. This is a safe type conversion.
    1. int smallnum = 654667;
    2. // Implicit conversion
    3. long bigNum = smallnum;
    1. class Base
    2. {
    3. public int num1 { get; set; }
    4. }
    5.  
    6. class Derived : Base
    7. {
    8. public int num2 { get; set; }
    9. }
    10.  
    11. class Program
    12. {
    13. static void Main(string[] args)
    14. {
    15. Derived d = new Derived();
    16. //Implicit Conversion
    17. Base b = d;
    18. }
    19. }
  2. Explicit conversion

    Explicit conversion is being done by using a cast operator. It includes conversion of larger data type to smaller data type and conversion of base class to derived classes. In this conversion information might be lost or conversion might not be succeed for some reasons. This is an un-safe type conversion.
    1. long bigNum = 654667;
    2. // Explicit conversion
    3. int smallnum = (int)bigNum;
    1. class Base
    2. {
    3. public int num1 { get; set; }
    4. }
    5.  
    6. class Derived : Base
    7. {
    8. public int num2 { get; set; }
    9. }
    10.  
    11. class Program
    12. {
    13. static void Main(string[] args)
    14. {
    15. Base b = new Base();
    16. //Explicit Conversion
    17. Derived d = (Derived)b;
    18. }
    19. }
  3. User-defined conversion

    User-defined conversion is performed by using special methods that you can define to enable explicit and implicit conversions. It includes conversion of class to struct or basic data type and struct to class or basic data type. Also, all conversions methods must be declared as static.
    1. class RationalNumber
    2. {
    3. int numerator;
    4. int denominator;
    5.  
    6. public RationalNumber(int num, int den)
    7. {
    8. numerator = num;
    9. denominator = den;
    10. }
    11.  
    12. public static implicit operator RationalNumber(int i)
    13. {
    14. // Rational Number equivalant of an int type has 1 as denominator
    15. RationalNumber rationalnum = new RationalNumber(i, 1);
    16. return rationalnum;
    17. }
    18.  
    19. public static explicit operator float(RationalNumber r)
    20. {
    21. float result = ((float)r.numerator) / r.denominator;
    22. return result;
    23. }
    24.  
    25. }
    26. class Program
    27. {
    28. static void Main(string[] args)
    29. {
    30. // Implicit Conversion from int to rational number
    31. RationalNumber rational1 = 23;
    32.  
    33. //Explicit Conversion from rational number to float
    34. RationalNumber rational2 = new RationalNumber(3, 2);
    35. float d = (float)rational2;
    36. }
    37. }

What is the Upcasting and Downcasting?

There are two more casting terms Upcasting and Downcasting. basically these are parts of Implicit conversion and Explicit conversion.
Implicit conversion of derived classes to base class is called Upcasting and Explicit conversion of base class to derived classes is called Downcasting.
  1. class Base
  2. {
  3. public int num1 { get; set; }
  4. }
  5.  
  6. class Derived : Base
  7. {
  8. public int num2 { get; set; }
  9. }
  10.  
  11. class Program
  12. {
  13. static void Main(string[] args)
  14. {
  15. Derived d1 = new Derived();
  16. //Upcasting
  17. Base b1 = d1;
  18.  
  19. Base b2 = new Base();
  20. //Downcasting
  21. Derived d2 = (Derived)b2;
  22. }
  23. }

Comments

Popular posts from this blog

Accessing File Stored in Windows Azure Blob Storage Using jQuery

Did you know it was possible to access the Windows Azure Blob Storage directly from JavaScript, for example using jQuery? At first, it sounds obvious, since Blobs are after all accessible from a public UR. But in practice, there is a very big hurdle: the Web browser’s Same Origine Policy or SOP, that restricts JavaScript code to accessing resources originating from the same site the script was loaded from. This means that you will never be able to load a Windows Azure Blob using XMLHttpRequest for example! Fortunately, there is a popular workaround called JSONP (“JSON with Padding”). The idea behind this technique is that the script tag is not submitted to the SOP: an HTML page can thus load a JavaScript file from any site. So, if you expose your data in an “executable” form in JavaScript, a page will be able to load this data using a script tag. For example: <script type=”text/javascript” src=”http://www.sandeepknarware.in/exemple.jsonp”> </script> But how can ...

Support for debugging lambda expressions with Visual Studio 2015

Anyone who uses LINQ (or lambdas in general) and the debugger will quickly discover the dreaded message “Expression cannot contain lambda expressions”. Lack of lambda support has been a limitation of the Visual Studio Debugger ever since Lambdas were added to C# and Visual Basic.  With visual studio 2015 Microsoft has added support for debugging lambda expressions. Let’s first look at an example, and then I’ll walk you through current limitations. Example To try this yourself, create a new C# Console app with this code: using System.Diagnostics; using System.Linq; class Program { static void Main() { float[] values = Enumerable.Range(0, 100).Select(i => (float)i / 10).ToArray(); Debugger.Break(); } } Then compile, start debugging, and add “values.Where(v => (int)v == 3).ToArray()” in the Watch window. You’ll be happy to see the same as what the screenshot above shows you. I am using Visual Studio 2015 Preview and it has some limitati...

gcAllowVeryLargeObjects Element

There are numerous new features coming with .NET 4.5 and here, on this blog, you can find several posts about it. But the feature we are goint to talk about today is very exciting, because we were waiting for it more than 10 years. Since .NET 1.0 the memory limit of .NET object is 2GB. This means you cannot for example create array which contains elements with more than 2GB in total. If try to create such array, you will get the OutOfMemoryException. Let’s see an example how to produce OutOfMemoryException. Before that Open Visual Studio 2012, and create C# Console Application, like picture below. First lets create simple struct with two double members like example below: 1 2 3 4 5 6 7 8 9 10 11 12 public struct ComplexNumber {      public double Re;      public double Im;      public ComplexNumber( double re, double im)      {    ...