Reputation: 392
I'm having an issue comparing 2 objects in an ASP.NET Project, I'm not sure if I am a beginner or what but this is my actual code:
private void CheckFriendshipStatus()
{
if (Object.ReferenceEquals(Session["UserId"].ToString(), Session["CurrentProfileId"].ToString()))
{
btnAddAsFriend.Visible = false;
}
else
{
DataTable dt1 = new DataTable();
string chkfriendRequest = "SELECT * FROM Friends WHERE (MyId='" + Session["UserId"].ToString() + "' and FriendId='" + Session["CurrentProfileId"].ToString() + "') OR (MyId='" + Session["CurrentProfileId"].ToString() + "' and FriendId='" + Session["UserId"].ToString() + "')";
Then I tried:
var obj1 = Session["UserId"].ToString();
var obj2 = Session["CurrentProfileId"].ToString();
if (obj1 == obj2)
{
btnAddAsFriend.Visible = false;
}
else
{
and then I tried setting the value to null first and then assigning the session values. I'm out of ideas, any other one will be highly appreciated
Upvotes: 0
Views: 1669
Reputation: 392
This Actually worked guys,
var obj1 = Session["UserId"].ToString();
var obj2 = Session["CurrentProfileId"].ToString();
if (obj1 == obj2)
{
btnAddAsFriend.Visible = false;
}
If this is happening to some of you that might be having the same code as step 1, this will resolve it!
Thank you all who took the time to waste it with me and help me! :)
Upvotes: 0
Reputation: 150108
If you put strings into Session, you can get them back out as strings by casting.
var obj1 = (string)Session["UserId"]
If obj1
happens to be null, calling obj1.ToString()
will cause a null reference exception. Casting as shown above will avoid that exception (though it may still be a logical error if one of them is null, depending on the conventions in your program).
If they are strings, you want to use the ==
operator. Object.ReferenceEquals()
returns true if the two variables refer to the exact same object. Due to string interning, this would "coincidentally" commonly give you the expected result anyhow, but it is possible to turn off string interning.
UPDATE:
Based on your clarifying comment, it's almost certain that one or both of the Session
variables you are calling .ToString()
on is null. Use the casting approach that I outline, and use a debugger to see which is null.
Upvotes: 1
Reputation: 120400
Either Session["UserId"]
or Session["CurrentProfileId"]
or btnAddAsFriend
is null. Can't tell which from the details provided.
Upvotes: 0