Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using "as bool?" instead of "object something = ViewState["hi"]"

Tags:

c#

So I'm going through old code (2.0) and I came across this:

object isReviewingValue = ViewState["IsReviewing"];

if (isReviewingValue is bool)
{
  return (bool)isReviewingValue;
}

My first thought was to us the "as" keyword to avoid the unneeded

(bool)isReviewingValue;

But "as" only works with non value types. No problem, I just went ahead and did this:

bool? isReviewingValue= ViewState["IsReviewing"] as bool?;
if (isReviewingValue.HasValue)
{
  return isReviewingValue.Value;
}

Question is: Besides looking a bit more readable, is this in fact better?

EDIT:

public Stopwatch AsRun()
{
  Stopwatch watch = new Stopwatch();

  watch.Start();
  for (Int32 loopCounter = 0; loopCounter < 10000; loopCounter++)
  {
    Object value = true;
    Boolean? test = value as Boolean?;
    if (test.HasValue)
    {
      Boolean something = test.Value;
    }
  }
  watch.Stop();

  return watch;
}

public Stopwatch ObjectIsRun()
{
  Stopwatch watch = new Stopwatch();

  watch.Start();
  for (Int32 loopCounter = 0; loopCounter < 10000; loopCounter++)
  {
    Object test = true;
    if (test is Boolean)
    {
      Boolean something = (Boolean)test;
    }
  }
  watch.Stop();

  return watch;
}

Answer: Turns out that with the above methods run in a test fashion, the original code is about 10 times faster.

like image 256
Programmin Tool Avatar asked Apr 20 '10 13:04

Programmin Tool


2 Answers

The coalesce operator will remove some code for you. To answer your question, as Jimmy made quite clear, the technical differences between the two are minuscule so use whichever you feel is better. Personally, I am inclined to use this method. I might be considered biased though...

private bool GetIsReviewing()
{
    return (ViewState["IsReviewing"] as bool?) ?? false;
}
like image 138
ChaosPandion Avatar answered Nov 08 '22 08:11

ChaosPandion


I think the first one is more readable , and it is faster as well [about 10 nanoseconds versus 100 nanoseconds, according to a test I just ran ;) (i.e. not going to slow your program down either way) ]

like image 34
Jimmy Avatar answered Nov 08 '22 07:11

Jimmy