4

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?

Ali
  • 5,286
  • 9
  • 33
  • 36
  • possible duplicate of [How should anonymous types be used in C#?](http://stackoverflow.com/questions/48668/how-should-anonymous-types-be-used-in-c) – nawfal Jul 15 '14 at 15:28

3 Answers3

8

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.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
2

Does grouping a sender and recipient together make sense outside this method? If so, consider creating a class for them. If not, I would usually use separate local variables, but I suspect that's mostly through habit.

I suspect what we've here got is a pair of local variables which are conceptually related. The relationship may not be strong enough to deserve a full type, but it's meaningful within the method. In some ways, using an anonymous type is a very neat way of making that pairing obvious. On the other hand, if your method is long enough that it really needs that extra level of clarity, perhaps you should break it up anyway.

Note that using an anonymous type makes some refactoring techniques harder because the type is only available with the method (without a bit of hackery).

I realise that this is a wishy-washy answer, but it does strike me that there's some merit in the overall idea - it's a bit like using a tuple in a functional language.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

Use local variables (i think this is what you meant) in this case.

Anonymous type should be use where you would need a standard name type but use it only for implementation purpose inside of a method. It removes the tedious work of creating a new type definition.

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

thinkbeforecoding
  • 6,668
  • 1
  • 29
  • 31