Tuples & Anonymous Types both are used to group related information, used when we look to group some information but avoid to create class.
Tuple Disadvantage
Members are not strongly typed, we need to remember data contained in Item1, Item2...
Anonymous Type Disadvantage
Type casting required
Tuple Disadvantage
Members are not strongly typed, we need to remember data contained in Item1, Item2...
Anonymous Type Disadvantage
Type casting required
class Program
{
static void Main(string[] args)
{
//Tuple call
string Personnelinfo = "Ram
Singh 39";
var PI =
PersonalInfo(Personnelinfo);
string FName = PI.Item1;
string LName = PI.Item2;
int Age = PI.Item3;
//Anonymous
Type call
var objPI = Cast(PersInfo(Personnelinfo), new { FirstName = "",
LastName = "", Age = 0 });
FName = objPI.FirstName;
LName = objPI.LastName;
Age = objPI.Age;
}
static Tuple<string, string, int> PersonalInfo(string PI)
{
string[] info = PI.Split(' ');
// Tuple
return Tuple.Create<string, string, int>(info[0], info[1], int.Parse(info[2]));
}
static object PersInfo(string PI)
{
string[] info = PI.Split(' ');
//Anonymous type
return new { FirstName = info[0], LastName = info[1], Age = info[2]
};
}
static T Cast<T>(object obj, T type)
{
return (T)obj;
}
}
No comments:
Post a Comment