Is casting the same thing as converting?

前端 未结 11 965
失恋的感觉
失恋的感觉 2020-11-27 17:01

In Jesse Liberty\'s Learning C# book, he says \"Objects of one type can be converted into objects of another type. This is called casting.\"

If you investigate the I

11条回答
  •  半阙折子戏
    2020-11-27 17:41

    Casting involves References

    List myList = new List();
    //up-cast
    IEnumerable myEnumerable = (IEnumerable) myList;
    //down-cast
    List myOtherList = (List) myEnumerable;
    

    Notice that operations against myList, such as adding an element, are reflected in myEnumerable and myOtherList. This is because they are all references (of varying types) to the same instance.

    Up-casting is safe. Down-casting can generate run-time errors if the programmer has made a mistake in the type. Safe down-casting is beyond the scope of this answer.

    Converting involves Instances

    List myList = new List();
    int[] myArray = myList.ToArray();
    

    myList is used to produce myArray. This is a non-destructive conversion (myList works perfectly fine after this operation). Also notice that operations against myList, such as adding an element, are not reflected in myArray. This is because they are completely seperate instances.

    decimal w = 1.1m;
    int x = (int)w;
    

    There are operations using the cast syntax in C# that are actually conversions.

提交回复
热议问题