Typecasting in C#

后端 未结 5 1122
Happy的楠姐
Happy的楠姐 2020-11-29 06:17

What is type casting, what\'s the use of it? How does it work?

5条回答
  •  抹茶落季
    2020-11-29 06:41

    Casting means creating a reference to an object that is of a different type to the reference you're currently holding. You can do upcasting or downcasting and each has different benefits.

    Upcasting:

    string greeting = "Hi Bob";
    object o = greeting;
    

    This creates a more general reference (object) from the more specific reference (string). Maybe you've written code that can handle any object, like this:

    Console.WriteLine("Type of o is " + o.GetType());
    

    That code doesn't need to be changed no matter what objects you set o to.

    Downcasting:

    object o = "Hi Bob";
    string greeting = (string)o;
    

    Here you want a more specific reference. You might know that the object is a string (you can test this e.g.:

    if (o is string)
    { do something }
    

    Now you can treat the reference as a string instead of an object. E.g. a string has a length (but an object doesn't), so you can say:

    Console.WriteLine("Length of string is " + greeting.length);
    

    Which you can't do with an object.

提交回复
热议问题