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);
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With