In previous post at Software Architecture – C# – 4.0 – New Feature – Tuple , I introduced Tuples. During a presentation Badar-one of my team mate asked me question that why we need a new type tuple-When there are already classes,structures,Array,ArrayList,List. So I posting my reply.
Actually Microsoft is growing C# as most prowerfull programming langauge, so they contionously extend the core language element. Tuple has been there in Pythone and F# previously, now with c# 4.0, it is also part of core c# syntyx.
Comparsion with Class/Structure:
So problem defination is that we want to group together related values/ types into one type.
First thing comes in mind to have Class and contain all elements to be grouped in side a class. Sounds good,but there are cases when there no objec t oriented concept related to grouping. Class comes with heavy concepts like Encapsulation,Pholymorphism,abstraction,inheritence,constructor and a lot more… So when grouping is required but there is no OO sense, then Tuples are best choice.
You may point out that Structures are also there. Again there have attached concepts like inheritence,constrcutor,methods,properties and lot more. So when just grouping is required but no Object oriented concepts, tuples are the best choices.
Comparsion with Array/ArrayList/List:
No..No you can’t compare Tuple with Array/ArrayList/List.Because of simple point that Tupe is treated as data type and Array/ArrayList/List are treated as data strcutures. Just visualise the basic course with “Data Structure” in BCS, you will know the differenc e. Array/Arraylist/List are affilated with general concepts of Data structure like sorting , searc hing and a lot more. For Tuple we don’t have any such concept. It is simple Grouping og related values/types.
Getting and Setting elements in tupes is totally different from other Data strcutures like Array,ArrayList/List.
Secondly, elements in array are not strongly types(Require a type casting),but elements of Tuples are strongly typed.