Type Conversion Method in C# | A Complete Tutorial
C Type Conversion Tutorial ACTE

Type Conversion Method in C# | A Complete Tutorial

Last updated on 02nd Feb 2022, Blog, Tutorials

About author

Manobala (C# Automation Tester )

Manobala is a C# automation tester and he has tons of experience in the areas of HTTP, SOAP/REST, VisualStudio, TFS, etc., CI/CD, functional, regression, and.NET technology stack. He spends most of his time researching technology and startups.

(5.0) | 19212 Ratings 1936
    • Introduction
    • C# Type Conversion
    • C# Type Conversion Methods
    • Type Conversion Methods
    • C# Type Conversion using Convert Class
    • C# Type Casting
    • C# Type Conversion utilizing Parse()
    • In C#, we can play out various types of Conversions
    • Conversion Operators
    • Advantage of Type Conversion
    • Conclusion

    Subscribe For Free Demo

    [custom_views_post_title]

      Introduction:-

      In this instructional exercise, we will find out with regards to the C# type change and its sorts with the assistance of models. The most common way of changing over the worth of one kind (int, float, twofold, and so forth) to one more sort is known as type Conversion.


      C# Type Conversion:-

      Type change is changing one sort of information over to another kind. It is otherwise called Type Casting. In C#, type projecting has two structures −


    • Certain sort Conversion – These changes are performed by C# in a kind safe way. For instance, are Conversions from more modest to bigger indispensable sorts and changes from inferred classes to base classes?

    • Express sort change – These Conversions are done unequivocally by clients utilizing the pre-characterized capacities. Express changes require a cast administrator.

    •  C# Type Conversion
      C# Type Conversion

      The accompanying model shows an express sort change −

        • utilizing System;
        • namespace TypeConversionApplication {
        • class ExplicitConversion {
        • static void Main(string[] args) {
        • twofold d = 5673.74;
        • int I;
        • // project was twofold to int.
        • I = (int)d;
        • Console.WriteLine(i);
        • Console.ReadKey();
        • }
        • }
        • }

      C# Type Conversion Methods:-

      C# provides the following built-in type conversion methods –


      Course Curriculum

      Learn Advanced C# Certification Training Course to Build Your Skills

      Weekday / Weekend BatchesSee Batch Details
        S No. Methods Description
        1 ToBoolean Converts a type to a Boolean value, where possible.
        2 ToByte Converts a type to a byte.
        3 ToChar Converts a type to a single Unicode character, where possible.
        4 ToDateTime Converts a type (integer or string type) to date-time structures.
        5 ToDecimal Converts a floating point or integer type to a decimal type.
        6 ToDouble Converts a type to a double type.
        7 ToInt16 Converts a type to a 16-bit integer.
        8 ToInt32 Converts a type to a 32-bit integer.
        9 ToInt64 Converts a type to a 64-bit integer.
        10 ToSbyte Converts a type to a signed byte type.
        11 ToSingle Converts a type to a small floating point number.
        12 ToString Converts a type to a string.
        13 ToType Converts a type to a specified type.
        14 ToUInt16 Converts a type to an unsigned int type.
        15 ToUInt32 Converts a type to an unsigned long type.
        16 ToUInt64 Converts a type to an unsigned big integer.

      Type Conversion Methods:-

      It is additionally conceivable to change over information types unequivocally by utilizing worked in techniques, like Convert.ToBoolean, Convert.ToDouble, Convert.ToString, Convert.ToInt32 (int) and Convert.ToInt64 (long):


    • Model,
    • int myInt = 10;
    • twofold myDouble = 5.25;
    • bool myBool = valid;

    • Console.WriteLine(Convert.ToString(myInt));//convert int to string
    • Console.WriteLine(Convert.ToDouble(myInt));//convert int to twofold
    • Console.WriteLine(Convert.ToInt32(myDouble));//convert twofold to int
    • Console.WriteLine(Convert.ToString(myBool));//convert bool to string

    • C# Type Conversion utilizing Convert Class:-

        Method Description
        ToBoolean() converts a type to a Boolean value
        ToChar() converts a type to a char type
        ToDouble() converts a type to a double type
        ToInt16() converts a type to a 16-bit int type
        ToString() converts a type to a string

      C# Type Conversion using Convert Class:-

      In C#, we can utilize the Convert class to perform type change. The Convert class gives different techniques to change one sort over to another.

      Projecting and type Conversions (C# Programming Guide)

      Since C# is statically-composed at order time, after a variable is proclaimed, it can’t be announced again or relegated a worth of another kind except if that type is certainly convertible to the variable’s sort. For instance, the string can’t be certainly changed over to int. Consequently, after you announce I as an int, you can’t allow the string “Hi” to it, as the accompanying code shows: int I; // mistake CS0029: Cannot certainly change over type ‘string’ to ‘int’ I = “Hi”;


      In any case, you could in some cases need to duplicate a worth into a variable or strategy boundary of another kind. For instance, you could have a whole number variable that you want to pass to a technique whose boundary is composed as twofold. Or on the other hand, you could have to appoint a class variable to a variable of a connection point type. These sorts of activities are called type changes. In C#, you can play out the accompanying sorts of changes:


    • Understood changes: No extraordinary punctuation is required because the Conversion generally succeeds and no information will be lost. Models incorporate changes from more modest to bigger necessary sorts, and Conversions from inferred classes to base classes.

    • Unequivocal changes (projects): Explicit Conversions require a cast articulation. Projecting is required when data may be lost in the Conversion, or when the change probably won’t prevail for different reasons. Run-of-the-mill models incorporate numeric change to a kind that has less accuracy or a more modest reach and Conversion of a base-class case to an inferred class.

    • Client characterized changes: User-characterized Conversions are performed by exceptional strategies that you can characterize to empower express and understood changes between custom kinds that don’t have a base class-inferred class relationship. For more data, see User-characterized Conversion administrators.

    • Conversions with aide classes: To change over between non-viable sorts, for example, numbers and Systems.DateTime objects, or hexadecimal strings and byte exhibits, you can utilize the System.BitConverter class, the System. Convert class, and the Parse strategies for the underlying numeric sorts, like Int32. Parse. For more data, perceive How to change over a byte exhibit to an int, How to change a string over to a number, and How to change over between hexadecimal strings and numeric sorts.

    • C# Type Casting:-

      Type Conversion happens when we relegate the worth of one information type to another. On the off chance that the information types are viable, C# does Automatic Type Conversion. On the off chance that not equivalent, then, at that point, they should be changed over unequivocally which is known as Explicit Type Conversion. For instance, appointing an int worth to a long factor.


       C# Type Casting
      C# Type Casting

      Course Curriculum

      Get JOB Oriented C# Training for Beginners By MNC Experts

      • Instructor-led Sessions
      • Real-life Case Studies
      • Assignments
      Explore Curriculum

      C# Type Conversion utilizing Parse():-

      In C#, we can likewise utilize the Parse() strategy to perform type Conversion. For the most part, while performing type Conversion between non-viable sorts like int and string, we use Parse().


      Model: Type Conversion utilizing Parse()

        • utilizing System;
        • namespace Conversion {
        • class Program {
        • static void Main(string[] args) {
        • string n = “100”;
        • // changing string over to int type
        • int a = int.Parse(n);
        • Console.WriteLine(“Original string esteem: “+n);
        • Console.WriteLine(“Converted int esteem: “+a);
        • Console.ReadLine();
        • }
        • }
        • }

        • Output:
        • Unique string esteem: 100
        • Changed over int esteem: 100
        • In the above model, we have changed over a string type to an int type.
        • // changing string over to int type
        • int a = int.Parse(n);
        • Here, the Parse() strategy changes the numeric string 100 over to a number worth.

      In C#, we can play out various types of Conversions:-

      Implicit Conversion:

      For the verifiable Conversion, there isn’t any requirement for the unique language structure. This kind of Conversion is protected; in this change, there isn’t any deficiency of the information. Understood Conversions incorporate the change of the little kind to huge necessary sorts, and from the determined class to the base class Conversion.


      Explicit Conversion (Type Caste):

      Explicit Conversion will be finished with the cast administrator (). We will do the projecting when there is what is going on of the information misfortune, or when the Conversion isn’t succeeded. There can be some other justification for the unequivocal Conversion. The case of the projecting is the Conversion of the numeric sort to less accuracy or more modest reach. Unequivocal Conversion additionally incorporates the change of the base-class occurrence to the determined class.


      User-Defined Conversion:

      We can do this Conversion by characterizing the technique. We can utilize the strategy to empower the unequivocally understood Conversion between the custom sort, which doesn’t have any relationship with the base-class or determined class.


      Conversion with the aide class:

      For the change of the non-viable sort like whole number and System.DateTime objects or hexadecimal strings and byte clusters, we can utilize System.BitConversion class, System. Convert class and the Parse strategies for the inherent numeric sort like as int32 Parse.


      Understood Conversion:

      We can undoubtedly comprehend and utilize the verifiable change. Here we will dole out the whole number to the twofold is known as the verifiable Conversion since we are haven’t lost any information in this change.


      Conversion Operators:-

      Conversion Operators have the accompanying properties:

    • Conversions pronounced as “understood” will happen consequently when it is required.
    • Conversions pronounced as “express” will require the cast to be called.
    • All the changes should be proclaimed as certain.

    • Conversion Operators
      Conversion Operators

      Advantage of Type Conversion:-

    • This is done to exploit specific elements of type orders or type portrayals.
    • It assists us with processing articulations containing factors of various information types.

    • C and C Plus Sample Resumes! Download & Edit, Get Noticed by Top Employers! Download

      Conclusion:-

      A wide cluster of administrators is furnished with the C# language, including numerous administrators that are recognizable to C and C++ developers. C# additionally gives administrators that go past C and C++, for example, administrators for performing full sensible assessments and administrators for acquiring type data. C# additionally gives a few procedures to improving your client characterized types so that they’re more straightforward to utilize. By over-burdening administrators for your sorts, you can give your sorts conduct that matches that of underlying kinds.


    Are you looking training with Right Jobs?

    Contact Us
    Get Training Quote for Free