Link to home
Start Free TrialLog in
Avatar of bfth1505
bfth1505

asked on

ASP.NET Session Class instance problem in Server Cluster with distributed sessions

I need to add properties, but it is not working very well.  What is wrong with this class?

namespace com.landsafe.eval
{
   public class UserKey
   {
      private readonly String name;
      private readonly String userid;

      public UserKey(String name, String userid)
      {
         this.name = name;
         this.userid = userid;
      }

      public String GetName()
      {
         return userid;
      }
   }
}

Also, it has to be used as a key for a Hashtable.  What changes are required for to be a Hashtable key?
Avatar of dstanley9
dstanley9

You need to overload Equals() the == operator, and GetHashCode() to see if twpo UserKey objects are equal if you want to use it as a HashTable key.  objects by default use ReferenceEquals for the == comparison.

http://msdn2.microsoft.com/en-US/library/336aedhh.aspx
sorry, that should be override, not overload.
Hi,
read this, probably it will solve the problem

http://www.codeproject.com/useritems/Property_Acccesors.asp

regards,
dZ
Avatar of Carl Tawn
Well, one thing that is wrong with it is that you are trying to change the values of "name" and "userid" in your UserKey method, however, they are both declared as "ReadOnly".
UsreKey() is the constructor.  You can set readonly field in the declaration or in a constructor (but nowhere else)
Doh, wasn't reading it properly ;)
Avatar of bfth1505

ASKER

Thanks for the input.  So what would it look like with all these changes?
What defines "equality" for your class?  Just the user ID?  A combination of the User ID and Name?  

Assuming it's just the user ID, add the following two methods:

            public override bool Equals(object obj)
            {
                return userid.Equals(obj);
            }
            public override int GetHashCode()
            {
                return userid.GetHashCode();
            }

Also, I was wrong; you don't need to override the equality operator; just Equals() and GetHashCode() to use it in a hashtable.
Also, it seems a bit odd that GetName() returns the userid (instead of the name), and the name field is never used.

In additon, it's generally clearer to use get/set accessors instead of get___() :

      public String Name
      {
         get
            {
                return userid;
            }
      }
Sorry, that should have been

            public override bool Equals(object obj)
            {
                UserKey userKey = obj as UserKey;
                    return userKey == null ? false : userid.Equals(userKey.userid);
            }
Put it all together and I'll award the points!
ASKER CERTIFIED SOLUTION
Avatar of dstanley9
dstanley9

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial