Question

I have a method, which returns abstract class:

    public static object CurrentInfo()
    {
        // some code here

        return new
        {
            URL = "www.mydomain.com",
            User = "Jack",
            Age = 20
        };
     }

When I use the method, I obtain an abstract-class result, so I take it into object (or var) type:

 object obj = MyClass.CurrentInfo();
 //var obj = MyClass.CurrentInfo(); // I also tried that

I cannot access the properties URL, Age and User from the obj object. If I try followings it cause error.

 string myUrl = obj.URL // the same form Age and User

Should I CAST it? But to what...? I would like to exclude the way of creating a new STRUCT.

Was it helpful?

Solution 2

If you want to retain the anonymous type, which as indicated makes it difficult to work with, then here is a solution for dealing with the returned object:

var obj = CurrentInfo();
System.Type type = obj.GetType();
string url = (string)type.GetProperty("URL").GetValue(obj, null);

OTHER TIPS

Create a class with those properties so you can properly access them then the return object can be a strongly-typed class rather than an anonymous one. This way you can access the properties of the object.

such as

public class Info
{
   public string URL {get; set;}
   public string User {get; set;}
   public int Age {get; set;}
}

public static Info CurrentInfo()
    {
        // some code here

        return new Info()
        {
            URL = "www.mydomain.com",
            User = "Jack",
            Age = 20
        };
     }

You could use the type

Tuple<string, string, int>

This is a named class that represents what you're trying to create, and it's already pre-built into the .NET framework so you don't need to create any new classes or structs.

You would write something like

Tuple<string, string, int> obj = Tuple.Create("www.mydomain.com", "Jack", 20);

See the MSDN documentation for a 3-argument tuple: http://msdn.microsoft.com/en-us/library/dd387150(v=vs.110).aspx

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top