Skip to content

Convert

Miguel Bernard edited this page Jun 22, 2021 · 4 revisions

Implicit cast

To simplify the usage of the library while providing strong consistency and typing many types support implicit cast to their less safe counterpart.

// NonEmptyString to string
string s = new NonEmptyString("SomeValue");

// CloudEvent<T> to CloudEvent
CloudEvent ce = new CloudEvent<UserCreated>(new UserCreated());

It's also possible to implicitly cast those objects to their more "type-safe" version. However, beware that these implicit casts will perform validation of the parameters being passed in and might throw an exception in case they are invalid.

NonEmptyString s = "test";
NonEmtpyString s2 = ""; // Throws an exception

var ce = new CloudEvent(CloudEventsSpecVersion.Default) { Data = new UserCreated };
CloudEvent<UserCreated> ceTyped = ce;

Cast to a different type

CloudEvent<T> also supports strong casting to a different type.

Beware that using this feature can cause runtime errors as there no way for the compiler to determine if the types are compatible at compile time. Use at your own risk.

To a more abstract type

// assuming that UserCreated and UserModified inherit from IEvent
var userCreated = new CloudEvent<UserCreated>(new UserCreated());
var userCreatedAsIEvent = c.Cast<IEvent>();

var userModified = new CloudEvent<UserModified>(new UserModified());
var list = new List<CloudEvent<IEvent>>();
list.Add(userCreatedAsIEvent);
list.Add(userModified.Cast<IEvent>());

To a more specific type

IEvent userCreated = new UserCreated();
var ceIEvent = new CloudEvent<IEvent>(userCreated);
var ceUserCreated = ceIEvent.Cast<UserCreated>();
Clone this wiki locally