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 SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

C# syntax for declaring a variable! 1

Status
Not open for further replies.

z07924

IS-IT--Management
Feb 18, 2002
122
0
0
GB
Dim li As New ListItem("Not Selected", "0")

dlAccessType.Items.Insert(0, li)

The above code is in VB.NET, I want to change the samthing in C#.NET. I don't know how to declare the li variable using C#.

If anybody knows, let me know.

Thanks in Advance.

 
Anyway Thanks, I have already found it.
 
Key thing to remember is that C# variable declaration is the reverse of VB. In VB you had variable name, *then* datatype. In C# it's datatype before variable name:
Code:
ListItem li;
li = new ListItem("Not Selected", "0");
or
Code:
ListItem li = null;
li = new ListItem("Not Selected", "0");
or
Code:
ListItem li = new ListItem("Not Selected", "0");
First way allocates memory for the variable, but no memory for it's contents. The next line then allocates memory for the contents by calling new (and passing it one of that datatype's constructors). If you execute any significant amount of code between declaration and allocation, the compiler might complain about an uninitialized variable. So you'd use the 2nd method:

2nd way allocates memory for the variable and explicitly tells the compiler that it doesn't contain anything. Second line is same as above.

3rd way is a way of doing both steps in one line (nice shortcut). But you need to watch out for your parameter validation code. If the caller of your method passes a parameter to you, and you validate it only to find out it's bad, you will have allocated all that memory to hold your ListItem for nothing. In which case the 2nd method is preferred because it would be faster (also known as lazy allocation).

Hope this helps.

Chip H.


If you want to get the best response to a question, please check out FAQ222-2244 first
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top