Upcast vs downcast9/3/2023 All of the objects in the Generic list will all be of the same type. A better way is to use a Generic list because with that we specify the type of objects that are inside the list. Normally we don’t use ArrayList as it is prone to errors made by programmers. MemoryStream will be automatically upcast to Stream in the example above.Ĭonsider another example. StreamReader reader = new StreamReader(new MemoryStream()) Therefore we can pass a new FileStream or a new MemoryStream. In the constructor of the StreamReader object we can pass any object who’s type derives from the Stream class. The Object Browser shows you that FileStream derives from Stream. If we have an object of type SteamReader we can see how this works. A stream could be a file or a memory stream. So the question is, when would I need to know how to do this? What’s a real-world example? Now here we are starting to hint at polymorphism. Both can access and modify the Height and Width for example. They have different views of that object. what's the point of limiting yourself?īoth text and sharp in the above code are referencing the same object but they are not the same. shape does not have access to FontSize or FontName, soo text and shape are both references to the same object in memory. Shape shape = text // upcasting - implicit conversion here So here is a bit more of a real-world example from Mosh Hamedani’s course at. Below we convert a circle reference to a shape reference (base class/parent class). An object reference can be implicitly converted to a base class reference. Below is some code you could try for yourself. Shape is the parent and circle is the child. Let’s say we have a class called Shape and a class called Circle. We will also look at the as and is keywords. Downcasting is the opposite: going from a base class to a derived class, down the tree. What is upcasting and downcasting? Upcasting is conversion from a derived (child) class to a base (parent) class.
0 Comments
Leave a Reply.AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |