Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is GetHashCode just cargo-cult here?

HttpContext.Current.Items["ctx_" + HttpContext.Current.GetHashCode().ToString("x")]

I see this exact code all ... over ... the ... place but I must be overlooking something. It's common in responses to these posts to question the appropriateness of using HttpContext, but no one points out that GetHashCode is redundant and a fixed string will do.

What am I overlooking here?


EDIT: The question is, GetHashCode() will be the same for every HttpContext.Current, so why use GetHashCode() in the four links I provided? Some of them are posts with quite a bit of work put into them, so I feel like perhaps they are addressing some threading or context issue I'm overlooking. I don't see why just HttpContext.Current.Items["ctx_"] wouldn't do exactly the same.

like image 447
shannon Avatar asked Nov 03 '22 00:11

shannon


1 Answers

This is horrible. For one, HttpContext.Current.Items is local to the current HttpContext anyway so need to attempt to make the keys "more unique". Second, depending on how this technique is used the keys will collide once in a while causing spurious, undebuggable failures.

If you need a unique key (maybe because you are developing a library), use a saner solution like Guid.NewGuid().ToString(). This is guaranteed to work and even simpler.

like image 182
usr Avatar answered Nov 15 '22 06:11

usr