-2

I got a disposable class with following constructor:

 public MyClass(bool allowed){
    if(allowed) return;
    else { // leave outer using }
}

And it is used like this

using (new MyClass(false))
{
   DoSomething();
}

Or like following

using (new MyClass(true))
{
   DoSomething();
}

How to achieve that only the one called with (true) will execute the block (aka DoSomething()) and if it is called with (false) it will not execute the block?

Best_Where_Gives
  • 481
  • 2
  • 22
  • 1. Pass the boolean value into the `DoSomething` method. 2. Store it at class level and check inside `DoSomething`. 3. Wrap the entire `using` block in an `if` check. There's a lot of options here, too broad really. This code feels a little smelly. – DavidG Oct 17 '18 at 12:23
  • Why is MyClass disposable in the first place? Why can't you make it not implement IDisposable and just return a boolean, and just use an if statement? – mason Oct 17 '18 at 12:23
  • `if (! allowed) throw new Something();` – bommelding Oct 17 '18 at 12:24
  • throw an exception inside the constructor – adjan Oct 17 '18 at 12:24
  • Even if you can do it, should you? At a casual glance, how do you think the code will read to another dev (or you in about 2 weeks time)? If it's non-obvious, then you shouldn't consider it. – spender Oct 17 '18 at 12:24
  • MyClass is actually a validator. – Best_Where_Gives Oct 17 '18 at 12:25
  • That doesn't help us, the question is still too opinion based, broad and unclear. – DavidG Oct 17 '18 at 12:25
  • "... is a validator" doesn't change anything. A `using() {}` block just isn't designed for flow control. – bommelding Oct 17 '18 at 12:26
  • @Best_Where_Gives: well, then provide a `Validate` method and check there the `bool` property and add the logic. Also, why a validator needs to implement `IDisposable`? Use it only if you use unmanaged resources. Not as replacement for your business logic. – Tim Schmelter Oct 17 '18 at 12:27

2 Answers2

1

Since the previous answer was not sufficient, I would suggest adding a public property to MyClass which can be used to get the boolean value and check against that in the using statement.

emagers
  • 841
  • 7
  • 13
0

Why not base on the value boolean

var b = true;// or false
using (new MyClass(b))
{
    if(b)
        DoSomething();
}
Antoine V
  • 6,998
  • 2
  • 11
  • 34