Since my application has to work with a lot of identifiers, I thought about abstracting them using a Id<T>
class. This class would work like a Guid, it has a CreateNew()
method and so on, but would create a different Id depending on the type of T.
Examples:
var id = Id<Individual>.CreateNew(); // == "INDIVIDUAL-12345"
var id = Id<Organization>.CreateNew(); // == "ORGANIZATION-67890"
Now, Individual
and Organization
implement the interface IUser
.
Now I would like my Id<> to handle different implementations, but this does not work.
i.e. consider the following class, using Ids:
class Transaction{
private Id<IUser> _sender;
private Id<IUser> _receiver;
private Amount _amount;
public Transaction(Id<IUser> sender, Id<IUser> receiver, Amount amount {...}
}
I would like to be able to call:
new Transaction(Id<Individual>.CreateNew(), Id<Organization>.CreateNew(), new Amount());
but this is not possible as the constructor requires the types to be Id<IUser>
. Can you think about any workaround?
Update
Thanks for the answers until now.
Id<IUser>
is just an example (and the content of IUser is not that important here), I'd like to support identifiers for many objects (10/15, more in the future?).
Id<T>
uses a static class as helper, called TypesMatcher, whose job is to translate a type to a prefix (i.e. "Individual", "Organization", "Transaction"..).
Id<T>.CreateNew()
looks more or less like this:
[Pure]
public static Id<T> CreateNew()
{
if (!TypesMatcher.IsSupported<T>()) throw new Exception($"Type {typeof(T)} is not supported.");
string prefix = TypesMatcher.GetPrefixForType<T>();
string body = Guid.NewGuid().ToString();
return new Id<T>($"{prefix}-{body}");
}