Is there any downside to a class like:
class Example1
{
protected string UserId = (string)Session["user"];
}
//versus
class Example2
{
protected string UserId;
public Example2()
{
UserId = (string)Session["user"];
}
}
If I always want to set this value is there any downside to Example1?
UPDATE:
Session[“user”] is set in the Global.asax Session_Start. So if this fails. Nothing should work anyways.
Your biggest problem is if this
protected string UserId = (string)Session["user"];fails. You have no recourse to degrade gracefully. By putting it in the constructor etc. You can check the Session and make a decision on what to do.As a general rule, I only try and put values that I know are going to succeed like
UserId = -1;etc. and then modify them in a code block when I need to. You never know when something is going to go wrong and you need to recover from it.