Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anonymous types VS Local variables, When should one be used?

Tags:

c#

.net

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?

like image 773
Ali Avatar asked Dec 23 '22 13:12

Ali


1 Answers

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:

  • you can't expose them through a method API
  • you can't mutate them (the members are read-only)

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 Message class and populate that.

like image 123
Marc Gravell Avatar answered Feb 01 '23 22:02

Marc Gravell