Is this redundant code?

I am updating the system and looking at another developer code (ASP.NET in C #).

I came across this:

private ReferralSearchFilterResults ReferralsMatched
{
    get
    {
        if (Session[SESSION_REFERRAL_SEARCHFILTERRESULTS] == null || Session[SESSION_REFERRAL_SEARCHFILTERRESULTS].GetType() != typeof(ReferralSearchFilterResults))
            return null;
        else
            return (ReferralSearchFilterResults)Session[SESSION_REFERRAL_SEARCHFILTERRESULTS];
    }
    set
    {
        if (value == null)
        {
            Session[SESSION_REFERRAL_SEARCHFILTERRESULTS] = value;
        }
        else if (value.GetType() == typeof(ReferralSearchFilterResults))
        {
            Session[SESSION_REFERRAL_SEARCHFILTERRESULTS] = value;
        }
    }

}

Is type checking on a setter unnecessary? Of course, if I set the property for something other than an object ReferralSearchFilterResults, the code will not even compile? Am I missing something, or am I right to think that this can only be achieved with:

set
{
    Session[SESSION_REFERRAL_SEARCHFILTERRESULTS] = value;
}
+5
source share
6 answers

ReferralSearchFilterResults . , value.GetType() Type , value. ReferralSearchFilterResults, typeof(ReferralSearchFilterResults).

, , . , , . .

+3

, - , -, ReferralSearchFilterResults.

+3

get

return Session[SESSION_REFERRAL_SEARCHFILTERRESULTS] as ReferralSearchFilterResults;

, ReferralSearchFilterResults, null.

+3

, . Setter , value ReferralSearchFilterResults.

, , is as Type.

private ReferralSearchFilterResults ReferralsMatched
{
    get
    {
        if (Session[SESSION_REFERRAL_SEARCHFILTERRESULTS] == null || !(Session[SESSION_REFERRAL_SEARCHFILTERRESULTS] is ReferralSearchFilterResults))
            return null;
        else
            return Session[SESSION_REFERRAL_SEARCHFILTERRESULTS] as ReferralSearchFilterResults;
    }
    set
    {
        Session[SESSION_REFERRAL_SEARCHFILTERRESULTS] = value;
    }

}
+1

, - . , ReferralSearchFilterResults . , , . , , ReferralSearchFilterResults.

But I would use Session.Remove instead of just setting the variable to null, since the session variable still exists in the http context if it is set to only null.

So:

set
{
      if (value == null)
            Session.Remove(SESSION_REFERRAL_SEARCHFILTERRESULTS);
      else
            Session[SESSION_REFERRAL_SEARCHFILTERRESULTS] = value;
}
+1
source

I can understand type checking in the get bit, but, as you say, in the installer you cannot pass anything that is not ReferralSearchFilterResults, since the code failed at compile time.

(Maybe some old habit, another developer)

0
source

All Articles