Loading [Contrib]/a11y/accessibility-menu.js
Back
Close

C# Professional - Basics & OOP - Exercises

talent-agile
15.7K views
Previous: ValueTypes - Exercises

Using casting operators

With C#, you can define custom casting implementation between two types. This implementation will be used when casting from one type to the other in your code.

// { autofold
using System;
// }
// User definition
// { autofold
public class User
{
public string FirstName { get; set; }
public string LastName { get; set; }
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Exercise : Implement an implicit and explicit casting

In the following exercise, you have two classes, Car and Vehicle.

The goal is to implement an implicit casting of Car to Vehicle. The casting must respect these guidelines:

  • The Vehicle.Type property value should be "Car"
  • The Vehicle.Name property should use the car properties to display all car information with the following format : Brand / Model (Year) / License Plate
Implement implicit casting
·// { autofold
using System;
namespace Casting
{
// }
public class Car
{
public string Brand { get; set; }
public string Model { get; set; }
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Be careful when implementing custom casting operators. They can be useful is certain situations, but using them is not very intuitive and can be misleading.

Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Go to tech.io
codingame x discord
Join the CodinGame community on Discord to chat about puzzle contributions, challenges, streams, blog articles - all that good stuff!
JOIN US ON DISCORD
Online Participants