Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to inline initialize exception's Data?

Tags:

c#

.net

I want to throw exception with additional data without creating exception variable. Something like this:

throw new Exception() { Data.Add("foo", "bar") };

Is it possible?

like image 231
Poma Avatar asked Nov 16 '25 22:11

Poma


1 Answers

It looks like you should be able to do that with:

throw new Exception { Data = { { "foo", "bar" } } };

(Assuming you're using C# 3, which has collection initializers...)

Of course you can do this in conjunction with constructor arguments:

throw new ArgumentException("paramName") { Data = { { "foo", "bar" } } };
like image 91
Jon Skeet Avatar answered Nov 18 '25 12:11

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!