To C#

  • Thread starter Thread starter RP
  • Start date Start date
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");
 
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
 
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.
...............................................................................................................
 
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");
 
Back
Top