Overview:
System.Object in the only way to return an anonymous type from a method (because anonymous types are really anonymous).- Anonymous type is extremely useful in linq queries because it allow you to construct type with several properties without declaring the type .
- We have to use dynamic keyword to get return object ( anonymous type ) from method.
Example:
- public static object MyMethod()
{
return new { firstName = "Saniul", lastName = "Naim" };
}
static void Main(string[] args)
{
dynamic obj = MyMethod();
Console.WriteLine(obj.firstName);
Console.WriteLine(obj.lastName);
Console.ReadLine();
}
Alternavite Idea:
- If we dont want to use dynamic keyword then we have to use casting.
public static object MyMethod()
{
return new { firstName = "Saniul", lastName = "Naim" };
}
static void Main(string[] args)
{
object obj = MyMethod();
var varOjb = Cast(obj, new { firstName = "", lastName = "" });
Console.WriteLine("{0} {1}", varOjb.firstName, varOjb.lastName);
Console.ReadLine();
}
static T Cast<T>(object objParam, T typeName)
{
return (T)objParam;
}
{
return new { firstName = "Saniul", lastName = "Naim" };
}
static void Main(string[] args)
{
object obj = MyMethod();
var varOjb = Cast(obj, new { firstName = "", lastName = "" });
Console.WriteLine("{0} {1}", varOjb.firstName, varOjb.lastName);
Console.ReadLine();
}
static T Cast<T>(object objParam, T typeName)
{
return (T)objParam;
}
Note:
- Sometime Tuple is very useful:
public static Tuple<string, string> TupleMethod()
{
return Tuple.Create("Saniul", "Naim");
}
static void Main(string[] args)
{
var obj = TupleMethod();
Console.WriteLine(obj.Item1);
Console.WriteLine(obj.Item2);
Console.ReadLine();
}
good.
ReplyDeletetnks
Deletevery useful
ReplyDeletetnks..
Delete