davidinho
davidinho

Reputation: 169

Unknown C# type

I've a method exMethod that return the value in this way:

return new {name = name, surname = surname};

and I use this code

var person = exMethod();

but at this point how can I access to its fields? I've tried with

person.name

but is thrown the exception

'object' does not contain a definition for 'name'

Upvotes: 2

Views: 687

Answers (3)

Amit
Amit

Reputation: 46323

If you have control over exMethod, modify it as Patrick suggests.

If you don't and must accept it as an Object use dynamic instead of var:

dynamic person = exMethod();
person.name;

Answer is worthless, comments are good, particularly @Servy's:

Anonymous classes are internal, so if it's in an API that you don't have access to then dynamic wouldn't work. It's only an option when you have control over the implementation of the method.

Upvotes: 0

Dhunt
Dhunt

Reputation: 1594

you could do

dynamic person = exMethod();

but not recommended and is 'the easy way out' and you wouldn't have any compile time errors then. Another solution could be to use reflection but that can be heavy.

The best (safest, best practice) idea is probably to create a class to define the type that is being returned

class Foo {
    public string name {get;set;}
    public string surname{get;set;}
}

return new Foo(){ name = name, surname = surname }

then you would be able to use those properties

Upvotes: 1

Patrick Hofman
Patrick Hofman

Reputation: 156938

Anonymous types can't be passed across the boundaries of a method without losing their type (they will revert to object). Since you can't cast it, you are stuck.

You have to create a type to expose that to the outside of the creating method. (I don't want to mention dynamic as a solution)

Upvotes: 11

Related Questions