Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Session.Count C#

Status
Not open for further replies.

IT4EVR

Programmer
Feb 15, 2006
462
US
I have an ASP.NET book I am going through and unfortunately all the code examples are in VB.NET. So I am in the process of translating everything to C# code. This publisher also does not publish any accompanying examples in C# for this particular book. Because I like the book so much I am going through the pains of translating everything.

One thing I'm learning is that you do a lot more casting in C# than in VB.NET. This particular segment is giving me an error. Please tell me what I am doing wrong.

In the VB.NET code we have:
Code:
If Session("Cart").Count = 0 Then
 'ETC
End If

Cart represents the cart items in session state. This is an e-commerce sample web site.

What would be the equivalent in C#?

In C# I am having trouble accessing the Count property of Session object. If I write Session.Count I get it but if I try to access it with Session["Cart"] I am not able to get a count property.

Please tell me how to fix this...thanks...
 
I'm finding that a lot of ASP.NET books are only written in VB.NET and I find this perplexing. Or the examples in the text of the book are in VB.NET but they will provide examples on their CD in C#.

This is why I liked the book "Building Your Own Web Site with ASP.NET" by Site Point. It provided examples side by side in both languages. The code worked and I went through very little pain and suffering.
 
In fact in VB.NET I had the same problem with this code. Session("Cart").Count does not work...you can only use Session.Count.

 
I think I found out what the problem was. Because the Session["Cart"] object had been cast earlier in code to a SortList I had to cast this object back to a SortedList to get the value.

Something like this did the trick:
Code:
if(((SortedList)Session["Cart"]).Count == 0)
{
  blah blah blah
}

Is this referred to as boxing and unboxing a variable?

I'm learning a great deal by translating this VB.NET Code to C#. It's painful yet it's helping me to understand both languages better.
 
Boxing transforms a value type (allocated on the stack) to a reference type (allocated on the heap). Unboxing is the reverse.
{
int i = 100;
object o = i; //Boxing
int x = (int)o; //Unboxing
}


Vince
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top