How to Return an Anonymous Type from a Method

Is there a way to return Anonymous Type from method?

Returning it as a System.Object is the only way to return an anonymous type from a method. Unfortunately there is no other way to do this since anonymous types were designed specifically to prevent their use in this way.

There are some tricks that you can do to in conjunction with returning an Object that allow you to get close. If you are interested in this workaround please read Can't return anonymous type from method? Really?.

Disclaimer: Even though the article I linked does show a workaround that doesn't mean it is a good idea to do it. I would strongly discourage you using this approach when creating a regular type would be safer and easier to understand.

Return Anonymous Type from a function

This is a very popular question. In general you cannot return an anonymous type due to the requirement of strong typing. However there are a couple of workarounds.

  1. Create a simple type to represent the return value. (See here and here). Make it simple by generating from usage.
  2. Create a helper method to cast to the anonymous type using a sample instance for casting.

Method that returns anonymous type C#

You shouldn't return an anonymous type. Instead you should create a regular named class and use that as return type.

Anonymous types are good when their scope is just inside the method itself. They have no use outside the method. How would you for example know the property names if their definition is not public? The only solution is to create a class.

If you still want to return an anonymous type, you should return object or dynamic, both I am not really happy about when using that as return type.


Regarding your update: you have to use the named types in the code initializing the instances too (probably LINQ). C# doesn't automatically convert anonymous types to named types.

Returning anonymous type in C#

You can't.

You can only return object, or container of objects, e.g. IEnumerable<object>, IList<object>, etc.

How to return an anonymous type from a trait method without using Box?

What is the correct way to return an Iterator (or any other trait)? covers all the present solutions. The one you haven't used is to replace closures with function pointers and then use a type alias (optionally wrapping in a newtype). This isn't always possible, but since you didn't provide a MCVE of your code, we can't tell if this will work for you or not:

use std::iter;

type Thing<T> = iter::Map<iter::Filter<T, fn(&i32) -> bool>, fn(i32) -> i32>;

trait IterExt: Iterator<Item = i32> {
fn thing(self) -> Thing<Self>
where
Self: Sized + 'static,
{
// self.filter(|&v| v > 10).map(|v| v * 2)
fn a(v: &i32) -> bool { *v > 10 }
fn b(v: i32) -> i32 { v * 2 }
self.filter(a as fn(&i32) -> bool).map(b as fn(i32) -> i32)
}
}

impl<I> IterExt for I
where
I: Iterator<Item = i32>,
{}

fn main() {}

Honestly, in these cases I would create a newtype wrapping the boxed trait object. That way, I have the flexibility to internally re-implement it with a non-boxed option in an API-compatible fashion when it becomes practical to do so.

Return an (Anonymous Type with a Function) from a Function - Is There a Better Way?

Since VB has no return type inference for generic methods, even where there is no ambiguity, there is no way of doing this.

You can have a strongly typed function that returns an anonymous type using generics but you cannot call it with inferred generics, you need to specify them explicitly.

Private Function Copy(Of T)(filePath as String, prototype As T) As T
Return New With { .To = … }
End Function

(Naming convention adapted to .NET)

This must be called as follows:

Dim nullAction As Action(Of String) = Nothing
Dim proto = New With { .To = nullAction }
Copy(firstFile, proto).To(secondFile)

Return anonymous type results?

I tend to go for this pattern:

public class DogWithBreed
{
public Dog Dog { get; set; }
public string BreedName { get; set; }
}

public IQueryable<DogWithBreed> GetDogsWithBreedNames()
{
var db = new DogDataContext(ConnectString);
var result = from d in db.Dogs
join b in db.Breeds on d.BreedId equals b.BreedId
select new DogWithBreed()
{
Dog = d,
BreedName = b.BreedName
};
return result;
}

It means you have an extra class, but it's quick and easy to code, easily extensible, reusable and type-safe.

Correct return type for Task of anonymous object from async method in C#

You shouldn't return an anonymous object from a public method in the first place.

Either return a Tuple as suggested by @Krzysztof Skowronek or better yet define a type and return an instance of this one:

public async Task<YourClass> GetStuff()
{
abClass ret = await DoSomethingAsync();
return new YourClass { Param1 = ret.a, Param2 = ret.b };
}

Any consumers of your class should thank you for doing this.



Related Topics



Leave a reply



Submit