C# Professional - Basics & OOP - Exercises
Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// {
using System;
// }
// User definition
// {
public class User
{
public string FirstName { get; set; }
public string LastName { get; set; }
public static implicit operator String(User user)
{
return $"{user.FirstName} {user.LastName}";
}
public static explicit operator User(string text)
{
int spaceIndex = text.IndexOf(" ");
if(spaceIndex >= 1)
{
return new User
{
FirstName = text.Substring(0, spaceIndex),
LastName = text.Substring(spaceIndex + 1)
};
}
return new User { LastName = text };
}
}
// }
public class Program
{
public static void Main(string[] args)
{
var user = new User {
FirstName = "John",
LastName = "Doe"
};
// implict casting
string userAsString = user;
Console.WriteLine($"userAsString: {userAsString}");
// explicit casting
var otherUser = (User)userAsString;
Console.WriteLine("User:");
Console.WriteLine($" First name: {otherUser.FirstName}");
Console.WriteLine($" Last name: {otherUser.LastName}");
}
Press desired key combination and then press ENTER.
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// {
using System;
namespace Casting
{
// }
public class Car
{
public string Brand { get; set; }
public string Model { get; set; }
public int Year { get; set; }
public string LicensePlate { get; set; }
public static implicit operator Vehicle(Car car)
{
return null;
}
// {
}
}
// }
Press desired key combination and then press ENTER.
1
using System;
Press desired key combination and then press ENTER.
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.
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content