I am not sure when I should use anonymous types instead of local variables in C#.
I have:
string fullMessage // This is the full message including sender and recipient names string sender = GetMessagePart(fullMessage, 'from'); string recipient = GetMessagePart(fullMessage, 'to'); //do some stuff and deliver the message
Should I use:
var msg = new { sender = GetMessagePart(fullMessage, 'from') recipient = GetMessagePart(fullMessage, 'to') };
Instead?
Do you mean statically typed variables? Note that anonymous types are statically typed…(removed due to question edit)There are 2 problems with C# anonymous types:
If you only need to know about the data within a single method, and it is read-only, then an anonymous type is handy (and this covers a lot of cases, in reality).
If you need to mutate the data or pass it out to a caller, then use either a bespoke class, or simple variables (etc).
In the case given, I can’t see a reason to use an anonymous type; if you just want the values, use the separate variable approach. If a ‘message’ has a defined meaning, declare a
Messageclass and populate that.