Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# any way for an anonymous class to escape an inner scope block?

i want to use an anonymous class but instantiate inside a using code block and have it escape the block. is this possible?

eg, i have

using (var s = something()) {
   var instance = new { AA = s.A };
   // ... lots of code
   Console.WriteLine(instance.AA);
}

And I would rather have something like:

var instance;  // <- nope, can't do this
using (var s = something()) {
   instance = new { AA = s.A };
}
// ... lots of code
Console.WriteLine(instance.AA);
like image 326
CoderBrien Avatar asked Jan 04 '23 10:01

CoderBrien


1 Answers

Easily done:

var instance = new { Name = default(string) };
using (whatever) 
{
  instance = new { Name = whatever.Whatever() };
}
...

But the better thing to do here is to create an actual class.

Or, in C# 7, consider using a tuple.

Now, if you want to get really fancy...

static R Using<A, R>(A resource, Func<A, R> body) where A : IDisposable
{
    using (resource) return body(resource);
}
...

var instance = Using(something(), s => new { AA = s.A });

But this seems silly. Just make a class!

like image 152
Eric Lippert Avatar answered Jan 23 '23 15:01

Eric Lippert