NieAR
NieAR

Reputation: 1445

Create instance of OperationAbortedException

How I can to create OperationAbortedException? This code does not work:

var ex = new OperationAbortedException("Cannot update event comment");

ERROR: Cannot access private constructor 'OperationAbortedException'.

Upvotes: 3

Views: 1251

Answers (3)

Jodrell
Jodrell

Reputation: 35716

If you are talking about the System.Data.OperationAbortedException then no, you can not construct an instance directly, there are no public consrtuctors.

If you really wanted to, you could use reflection with the method described in this answer, but I reccomend that you do not. It would be a corruption of the framework's design.


Here is the code you could use but, please don't.

var ctor = typeof(OperationAbortException).GetConstructor(
    BindingFlags.NonPublic|BindingFlags.Instance,
    null, 
    new Type[0], 
    null);
var instance = (OperationAbortException)ctor.Invoke(null);

You'd have to work out which private constructor to use, if there is more than one, and which properties should be set to what. There is no garauntee that this behaviour would persist in later framework versions.

Upvotes: 2

Christian.K
Christian.K

Reputation: 49260

The System.Data.OperationAbortException-class (I'm assuming you mean this one, as you didn't fully qualify it in your question). has no public constructor and is sealed. These are strong hints that the framework designers didn't want you to use that exception for your own purposes. Presumably, because some inner workings of the framework would get confused if you did.

You should use a different exception for your purposes. From the message text you pass the following existing exceptions come to mind:

When selecting an existing exception from the .NET framework, make sure you not just select it by the name of the class alone. Make sure you read the respective MSDN page to understand the (original) intend for the exception. The respective documentation always starts with the words "The exception that is throw ...". If you find that text to match your intend, reuse the exception from the framework (or derive from it for finer control when eventually catching the exception).

Or create your own exception type, if you must.

Upvotes: 10

Sjoerd
Sjoerd

Reputation: 75619

This is not possible. OperationAbortedException has a private constructor and an internal static method which calls that constructor. It is not possible to create a new OperationAbortedException from another assembly.

Upvotes: 1

Related Questions