Tuesday, May 26, 2015

The ternary operator can come in handy in conditionally prepping a using statement in C#.

public void EnableOrDisableUser(User user, bool isToEnable)
{
   using (IFoo foo = _bar.CreateThing(isToEnable ? _constants.On : _constants.Off)
   {
      foo.Whatever(user, isToEnable);
   }
}

 
 

What is above seems superior to...

public void EnableOrDisableUser(User user, bool isToEnable)
{
   if(isToEnable)
   {
      using (IFoo foo = _bar.CreateThing(_constants.On)
      {
         foo.Whatever(user, true);
      }
   } else {
      using (IFoo foo = _bar.CreateThing(_constants.Off)
      {
         foo.Whatever(user, false);
      }
   }
}

No comments:

Post a Comment