3 ms·
What you're having me do there is create a new type for each different reply type. Generics mean that I can create Reply<T>{ T ReplyData; bool TheCa
by AndrewDucker 14y ago
What you're having me do there is create a new type for each different reply type. Generics mean that I can create
Reply<T>{
T ReplyData;
bool TheCallWorked;
string AssociatedMessage;
// other stuff here
}
and that's it - I can now have a reply that bundles up any type I like. My GetAddress function can return a Reply<Address>, my GetCustomerAge function can return a Reply<int>, etc.
Whereas you're having me recreate that boilerplate for every different reply type - which means that if the information needed for a Reply changes, or I have to make a fix to the associated code, I need to change every instance of it.
- grey-area 14y agoYou could use embedding to avoid writing code for an interface more than once if you have shared behaviour or state between types. You could reproduce your example above using a base reply type with ReplyData as an empty interface{} ptr (you'd have to wrap built-ins like int) and accessible fields. You could attach functions to that and only change them once and extend by embedding it in other special types of Reply if you wished. Typically though you'd have a base reply with bool and string say, and then extend that with other types of reply which make sense in certain situations rather than a generic payload which could be anything - so make ReplyData or a Reply type conform to an interface to ensure it does what your receiving methods want.
- AndrewDucker 14y agoSo, I think I've clearly shown where Generics are useful - you can use them to avoid having to create new classes that share very similar functionality, except for the type they operate upon. You can do the same things without them - but you have to write separate code for each type you deal with.
- grey-area 14y agoThanks for taking the time to explain more fully what you would use them for - not entirely convinced I'd find much use for them because of the built-in containers which operate on any type, but will read up on C# generics to find out more.