S
S
sdramare2011-07-21 14:36:51
.NET
sdramare, 2011-07-21 14:36:51

Study in C#: Create a strongly typed delegate that returns an anonymous type

Hey Habr.

Do you want a simple etude in C#?

Let's say we have an anonymous type new{ Name = "aaa", Number = 123 }

How do we make a getAnonimusInstance delegate that returns an anonymous type object?
Those. to compile and run

  1. var a = getAnonimusInstance();
  2. Console.WriteLine(a.Name);
  3. var b = getAnonimusInstance();
  4. Console.WriteLine(b.Number == a.Number); //где a и b имеют анонимный тип, описанный выше.
* This source code was highlighted with Source Code Highlighter.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
int02h, 2011-07-21
@int02h


dynamic GetAnonimusInstance()
{
  return new {Name = "aaa", Number = 123};
}

Isn't it?

P
PashaPash, 2011-07-21
@PashaPash

class Program
{
  static object ReturnAnonymous()
  {
    return new { Name = "aaa", Number = 123 };
  }
  static Func<T> Cast<T>(object obj, T type)
  {
    return () => (T)obj;
  }
  static void Main(string[] args)
  {
    object o = ReturnAnonymous();
    var getAnonimusInstance = Cast(o, new { Name = "", Number = 0 });
    var a = getAnonimusInstance();
    Console.WriteLine(a.Name);
    var b = getAnonimusInstance();
    Console.WriteLine(b.Number == a.Number); //где a и b имеют анонимный тип, описанный выше.
  }
}
* This source code was highlighted with Source Code Highlighter.

Wrote before clarification about 3.5, to adapt laziness.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question