Answered Anonymous type and Custom Type

  • Wednesday, January 09, 2013 8:59 PM
     
     

    Are there any 'rules' when i should use an anonymous type over a custom type? From what ive read anonymous types and custom types are almost the same but can cause bugs. That said some recommend using custom types when you know what data you require from multiple tables?

    Could anyone clarify or give some pointers?

    Thanks

All Replies

  • Wednesday, January 09, 2013 9:49 PM
     
     Answered

    In general, I only recommend using anonymous types if you're going to use the results within the same method.  If you're going to "persist" or pass the data into another method, display it, etc - I'd make a custom type.


    Reed Copsey, Jr. - http://reedcopsey.com
    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".

  • Thursday, January 10, 2013 3:53 PM
     
      Has Code

    When you have your object model in your project, generally you are operating with the references of this objects, but there are some case scenarios when you need a type of object which is little bit different rather your classes. var keyword can help you create your custom object, or even list of custome objects as anonymous type without additional coding or operations.

    Also anonymous types are used to shorten your code: for example instead of

    Dictionary<string, List<int, string>> x = new Dictionary<string, List<int, string>>();

    you can do

    var x = new Dictionary<string, List<int, string>>();


    Please Mark as Reply and Vote as Helpful if I helped.

    Also please visit my blog http://msguy.net/

  • Thursday, January 10, 2013 4:14 PM
     
     Answered

    Hi,
    Annonymous types generally are used in LINQ queries and the resultset we use in that function itself.
    When you need collection of specific type then you should use Custom type.

    For more information about the scenario when to use annonymous types please visit this link :

    http://msdn.microsoft.com/en-us/library/bb397696.aspx


    One good question is equivalent to ten best answers.