Looking for Better Way to Write Property

  • Thread starter Thread starter Jonathan Wood
  • Start date Start date
J

Jonathan Wood

Greetings,

I often find myself writing public properties in my ASP.NET code and I need
the ability to robustly handle cases where the property has not been set.

So I often end up with code like this:

public Guid PresenterID
{
get
{
object obj = ViewState["PresenterID"];
if (obj == null)
return null;
return (Guid)obj;
}
set { ViewState["PresenterID"] = value; }
}

My get seem overly complex because if I typecast the result of ViewState, I
get an error if it's null. I think I can use the as keyword to return
nullable datatypes whether they are null or not. But for non-nullable data
types, it seems like extra code is needed to workaround C#'s seemingly
arbitrary limitations.

I know it's not a lot of code, but I have to do something like this so
often. Can anyone offer a more efficient way to write this code?

Thanks.

Jonathan
 
Er... Well, actually, looks like that code wouldn't compile since I was
returning null and Guid isn't nullable. More of the same, unfortunately.

Jonathan
 
Maybe you should store Nullable<Guid> into viewstate.

Er... Well, actually, looks like that code wouldn't compile since I was
returning null and Guid isn't nullable. More of the same, unfortunately.

Jonathan


Greetings,
I often find myself writing public properties in my ASP.NET code and I
need the ability to robustly handle cases where the property has not been
set.
So I often end up with code like this:
public Guid PresenterID
{
 get
 {
  object obj = ViewState["PresenterID"];
  if (obj == null)
   return null;
  return (Guid)obj;
 }
 set { ViewState["PresenterID"] = value; }
}
My get seem overly complex because if I typecast the result of ViewState,
I get an error if it's null. I think I can use the as keyword to return
nullable datatypes whether they are null or not. But for non-nullable data
types, it seems like extra code is needed to workaround C#'s seemingly
arbitrary limitations.
I know it's not a lot of code, but I have to do something like this so
often. Can anyone offer a more efficient way to write this code?

Jonathan
 
Kalpesh,
return (ViewState["PresenterID"] as Guid);

That would be a nice, simple fix wouldn't it? But it won't compile (Guid is
not nullable).
Maybe you should store Nullable<Guid> into viewstate.

Maybe. I'm not familiar with that. I'll poke around.

Thanks.

Jonathan
 
Kalpesh,
return (ViewState["PresenterID"] as Guid);

That would be a nice, simple fix wouldn't it? But it won't compile (Guid is
not nullable).

Regardless of whether the value was nullable or not nullable when you
boxed it, you can always unbox it into a nullabe value, and check for
null. So:

ViewState["PresentedID"] = Guid.NewGuid(); // not nullable
...
Guid? maybeGuid = ViewState["PresentedID"] as Guid?; // still works,
null unboxes to null
if (maybeGuid != null)
{
Guid guid = (Guid)maybeGuid;
}
 
Back
Top