![]() ![]() A downcast requires a cast expression with the following syntax: (T)E Code language: C# ( cs ) Code language: plaintext ( plaintext ) DowncastingĪ downcast operation creates a subclass reference from a base class reference. ![]() The following statement will cause a compile-time error: person.JobTitle Code language: C# ( cs )Įrror: 'Person' does not contain a definition for 'JobTitle'. For example, it can only access the Name property but cannot access the JobTitle property of the object. The object itself does not change.Īlthough the person and employee variables refer to the same object, the person has a more restrictive view on that object. Both employee and person variable reference the same Employee‘s object. Third, assign the object referenced by the employee variable to a reference of the Person class.Īfter upcasting, the variable person still references the same Employee‘s object.Second, create a new instance of the Employee class and assign it to the employee variable.The Person class is a base class and the Employee class is a subclass. First, define the Employee class that inherits from the Person class.Person person = employee Code language: C# ( cs ) } Code language: C# ( cs ) var employee = new Employee() A downcast only succeeds if the objects are compatible types.Īn upcast creates a base class reference from a subclass reference. Explicitly downcast to a subclass reference.Implicitly upcast to a base class reference.Also, you cannot reassign a value of another type to the variable unless that type is implicitly compatible with the variable’s type. It means that after you declare a variable, you cannot redeclare it. Introduction to C# castingĬ# is a statically-typed programming language. Summary: in this tutorial, you’ll learn about the C# casting including upcasting and downcasting. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |