andrewlock / StronglyTypedId

A Rosyln-powered generator for strongly-typed IDs
MIT License
1.52k stars 80 forks source link

generate cast operator #68

Closed hjrb closed 9 months ago

hjrb commented 2 years ago

Hi, first of all: an outstanding library! Have you considered adding code generation for cast operators? Example [StronglyTypedId] public partial struct UserID { // addtionally generated public static implicit operator int(UserID userID) => userID.Value; public static explicit operator UserID(int i) => new UserID(i);

It would be userful when using (int) constants // without StronglyTypedId public static class Constants { const int SpecialUserID=4711; } ... switch (item.UserID) { case Constants.SpecialUserID: // .... }

After migrating user ID to StronglyTypedID one would need to change the code to switch (item.UserID.Value) { case Constants.SpecialUserID: // .... }

or make item.UserID a strongly typed ID. But that is often no so easy as this might come from DB DTO etc. If the above cast operators would be generated, that code would still compile. Also //.. public static readonly UserID SpecialUser = (UserID)4711 looks much nicer as public static readonly UserID SpecialUser = new UserID(4711)

I wonder why MS hasn't added something similar as StronglyTypedId to the compiler. That would really be a benefit. But so far we have your great library :-)

kcadduk commented 2 years ago

+1 :)

dariusz-wozniak commented 2 years ago

Yes, would be really nice to see it action :)

andrewlock commented 9 months ago

Sorry for the delay with this šŸ˜³. To be honest I got overwhelmed with how to handle the big range of feature requests and options. I think I've found an answer in the big redesign of the library in this PR:

The main idea is to make the library much more maintainable while also giving people a mechanism to customise the generated IDs as much as they like. This will make it easy to make changes like this that I don't necessarily want to be in the core library šŸ™‚