Anonymous types VS Local variables, when to use?

I'm 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

+4
source share
3 answers

Do you mean statically typed variables? Please note that anonymous types are statically typed ... (removed due to question editing)

There are two problems with anonymous C # types:

  • you cannot provide them through the method API
  • you cannot mutate them (members are read-only)

If you only need to know the data within a single method, and it is read-only, then the anonymous type is convenient (and this actually covers many cases).

If you need to mutate data or pass it to the caller, use either a custom class or simple variables (etc.).

In this case, I see no reason to use an anonymous type; if you just want values, use a separate approach to the variable. If β€œmessage” has a specific meaning, declare the Message class and populate it.

+8
source

Does the grouping of the sender and the receiver combine outside this method? If so, consider creating a class for them. If not, I would usually use separate local variables, but I suspect it is mostly out of habit.

I suspect we have a couple of local variables here that are conceptually related. Relations may not be strong enough to merit the full type, but it makes sense within the framework of the method. In a sense, using an anonymous type is a very simple way to make this connection obvious. On the other hand, if your method is long enough to really need this additional level of clarity, you might still need to break it.

Please note that using an anonymous type makes some refactoring methods more complicated, because the type is only accessible using the method (without any hacker).

I understand that this is an unsafe answer, but it seems to me that there is some merit in the general idea - it is a bit like using a tuple in a functional language.

+2
source

Use local variables (I think this is exactly what you had in mind) in this case.

An anonymous type should be used where you need a standard name type, but use it only for implementation purposes inside the method. It removes the tedious job of creating a new type definition.

You don't need a type here, so don't use an anonymous type.

+1
source

All Articles