Cast versus parse

前端 未结 4 700
广开言路
广开言路 2021-02-14 14:19

I\'ve read a few related questions regarding this topic however none of them are making sense to me. As I understand it, in some cases you can use cast and parse interchangeably

相关标签:
4条回答
  • 2021-02-14 14:22

    You generally use Parse() on a string whose value represents a valid value of the type to which you are converting.

    Casting, on the other hand, is better used when you have an object of a derived type but stored in a base variable, and need to use it as its more specific type.

    That is, if you have "1234" you can Parse() that into an int. But if you have

    object variable = 1234;
    

    You should cast it to get it back as an int.

    0 讨论(0)
  • 2021-02-14 14:26

    Casting : is conversion of an object from a similar datatype; like from int to double or from decimal to int. Casting does not create a new object, It will only assign a reference of one datatype to reference of another datatype, only if its assignable.

    Parsing : Parsing, on the other side, is converting from one data type to another, like from string to int for example. This Creates a new Object, and returns reference to it.

    In a nutshell, Casting will not create a new object, but deal with the same object reference, whereas parsing create a new object, and doesn't touch the old object in any way.

    0 讨论(0)
  • 2021-02-14 14:27

    Casting is more of a conversion of an object from a similar type. A good example is float to integer, or double to decimal. Parsing is just that; parsing. The definition or use of parsing is a bit more broad. You could write a Parse method in your own object similar to that of int.Parse or int.TryParse to convert a string to your object type. Parsing could also refer to things such as string manipulation to gather the data you need from any given string. "Parsing" does not necessarily relate to "Casting".

    Another good example of casting is when using inheritance or interfaces.

    public interface ICar {
        // ...
    }
    
    public class Corvette : ICar {
        // ...
    }
    
    public void Foo() {
        Corvette mycar = new Corvette();
        // Now do a cast
        ICar = (ICar)mycar;
    }
    
    0 讨论(0)
  • 2021-02-14 14:43

    Have a look here, at Mark Gravell's comprehensive answer (will answer you about converting too..).

    0 讨论(0)
提交回复
热议问题