To C#

R

RP

Please help converting following VB code to C#. My attempted C# code
is given below:

[VB Code]
If Session("Cart") Is Nothing Then
Session.Add("Cart",New SortedList)
End If
Return CType(Session("Cart"),SortedList)
----------------------------------------------------------------
[Attempted C# Code]
If (Session("Cart") == "")
Session.Add("Cart",new SortedList)

return SortedList Session("Cart");
 
C

Christof Nordiek

RP said:
Please help converting following VB code to C#. My attempted C# code
is given below:

[VB Code]
If Session("Cart") Is Nothing Then
Session.Add("Cart",New SortedList)
End If
Return CType(Session("Cart"),SortedList)

1. C# is case sensitive. If must be if.
2. Session("Cart") in your VB-Examble is not a fuction call, but an access
to a default property, wich is an indexer in C#. You have to call it with []
instead of () (like array element access).

(I assume Session here is the Session-object of ASP.NET. If it is a method
here, then calling with () is right.)
Session.Add("Cart",new SortedList)

3. Constructors (as well as methods) have allways to be called with
parantheses, even if the parameterlist ist empty.
return SortedList Session("Cart");

4. To Cast to another type, set the typename in parantheses before the
expression.

[Good C# Code]
if (Session["Cart"] == null)
Session.Add("Cart", new SortedList);

return (SortedList)Session("Cart");

HTH
Christof
 
R

RP

Christof,

Your code needed some correction. I modified like this and it worked:
=======================================
if (Session["Cart"]==null)
{
Session.Add("Cart",new SortedList());
}
return (SortedList) Session["Cart"];
=======================================
Thanks for your help.
...............................................................................................................
 
M

Michael S

My take:

{
SortedList list = (SortedList)Session["Cart"];
if (list == null)
{
list = new SortedList();
Session["Cart"] = list;
}
return list;
}

- Michael Starberg

RP said:
Christof,

Your code needed some correction. I modified like this and it worked:
=======================================
if (Session["Cart"]==null)
{
Session.Add("Cart",new SortedList());
}
return (SortedList) Session["Cart"];
=======================================
Thanks for your help.
..............................................................................................................
[Good C# Code]
if (Session["Cart"] == null)
Session.Add("Cart", new SortedList);

return (SortedList)Session("Cart");
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top