Continuing what Phil @ Haacked started about ASP.NET control properties that are backed by viewstate, meaning property values are saved to viewstate and retrieved as needed. Anyway, I figured I'll expand on his post and elaborate on what I call "more than one way to skin code".
As simple as this may be, I have implemented them in several ways without even thinking about the pros and cons, oh wait - thats what I always do. Do we really think about the disadvantages and advantages of code snippets as we write them? do we spend extra minutes to determine other means and ways on writing sections of our code?
Following up with Phil's sample codes, there are definitely other ways that you can achieve similar results. Jeff from CodingHorror pointed out the String.IsNullOrEmpty() method - he didn't exactly but I figured thats what he meant, this method indicates whether a string object is null reference or an Empty string. It will return true if the value is a null reference or Empty string otherwise you will get a false response. Since we are checking if our viewstate is empty - we can't check if its null because its not nullable or is it? Sample code.
return (bool)(!String.IsNullOrEmpty(ViewState["WillSucceed"].ToString()));
Will this work if it is not set? NO! you are probably going to get an "object reference not set to an ...." error. why? Because ViewState[...] is null - it can be null. Solution:
Now that we got that out of the way, let's try using the conditional operator(?:) and Phil's null coalescing operator idea.
return ViewState["WillSucceed"] != null ? true : false;
what do we get? Results! So using the conditional operator (?:) works great! Now lets try the null coalescing operator (??);
return (bool) (ViewState["WillSucceed"] ?? false);
Notice the braces/brackets around the viewstate and the operator is separate from the casting, if you ignore that and try to execute it "Sample code below", you will end up with an error message because the ?? operator can not be applied to bool type operands.
return (bool)ViewState["WillSucceed"] ?? false;
The point here is that if we spend a few extra seconds thinking about snippets, we may be able to come up with a better one, therefore, gradually making us better coders.
Thanks to Phil, for bringing up this excellent point.