|
Use a for loop if you need indexing. Use foreach if you don't need indexing and you like syntax candy.
Tech, life, family, faith: Give me a visit.
I'm currently blogging about: Homosexuality in Christianity
Judah Himango
|
|
|
|
|
It isn't about whether you "like syntax candy," it is about whether you like writing quality code. See Jan Larsen's reply for more insight.
Matt Gerrans
|
|
|
|
|
I'm not against using foreach, I use it quite a lot in my code. I just don't agree that 'foreach' is quality where 'for' is not. Both are easily recognizable by any novice programmer. As I said to the origin poster, if you need an index, you might as well be using for instead of foreach.
The IEnumerable idea is cool, and gets even better with C# 2.0's iterators with the yield keyword (allowing you to, basically, write co-routines). Coupled with foreach, it is really great. That doesn't mean we should never use the 'for' keyword.
My 'syntax candy' statement wasn't meant to belittle IEnumerable or foreach keyword; I'm merely saying that it is a simple syntax expression that does a lot under the hood (initialize an Enumerator, call the appropriate method calls each loop, and return the next object in the enumeration). You could call your own GetNext() and other appropriate IEnumerator functions yourself, 'foreach' is syntax candy that allows you to forgo typing all that.
Tech, life, family, faith: Give me a visit.
I'm currently blogging about: Homosexuality in Christianity
Judah Himango
|
|
|
|
|
Judah Himango wrote:
My 'syntax candy' statement wasn't meant to belittle IEnumerable or foreach keyword; I'm merely saying that it is a simple syntax expression that does a lot under the hood (initialize an Enumerator, call the appropriate method calls each loop, and return the next object in the enumeration). You could call your own GetNext() and other appropriate IEnumerator functions yourself, 'foreach' is syntax candy that allows you to forgo typing all that.
Basically, that's what high level languages are all about , I've done my share of Java programming, and I can assure you that I don't miss this:
for (Iterator i = myList.iterator(); i.hasNext();)
{
String tmp = (String) i.next();
}
I'd rather do this:
foreach(String tmp in myList)
{
}
Eye candy maybe, but much clearer, and I guess the ease of use, has got more inexperienced programmers to use the correct iterating technique.
I'm not joking, I've had colleques that would use this on a linked list:
for (int i = 0; i < myList.size(); i++)
{
String tmp = (String) myList.get(i);
}
"God doesn't play dice" - Albert Einstein
"God not only plays dice, He sometimes throws the dices where they cannot be seen" - Niels Bohr
|
|
|
|
|
foreach is great when you're abstracting your code. Indexing is purely for lists, and if you're doing a foreach on an IEnumerable , then you're always sure to get the maximum performance. Consider the performance issues on indexing eg. a linked list or a binary tree.
I'm always declaring my collection member variables as the lowest denominator. Eg. if I need a map, then I'm declaring an IDictionary , and when I'm iterating through the elements, I'll use a foreach loop.
This means that if I am to use a counter, then I have to do it the ugly way.
"God doesn't play dice" - Albert Einstein
"God not only plays dice, He sometimes throws the dices where they cannot be seen" - Niels Bohr
|
|
|
|
|
You can use IndexOf property of the collection you use, but since you're using foreach, there's no reason to think about indexes.
|
|
|
|
|
ltinka wrote:
You can use IndexOf property of the collection you use
Well, not really since there is no definite index in a map. Talking lists I definately agree, in a linked list, IndexOf() would trigger a reiteration, so it would have been better to use indexing in the first place.
"God doesn't play dice" - Albert Einstein
"God not only plays dice, He sometimes throws the dices where they cannot be seen" - Niels Bohr
|
|
|
|
|
cazzz wrote:
Is there any reason to use a foreach instead off a for loop?
Using foreach will automatically cast an item in the collection to right type.
Example:
for (int i = 0; i < 8; ++i)
{
Customer cust = (Customer)customers[i];
}
instead
foreach (Customer cust in customers)
{
}
Use foreach when you just want to iterate over all items and don't care about order or which item is the current item. Handle special behaviour inside a class and not in the calling code according to classic OO principles.
Example:
for (int i = 0; i < 8; ++i)
{
if (i == 4)
{
Customer cust = (Customer)customers[i];
DoSumthingWithCustomer(cust);
}
}
instead
foreach (Customer cust in customers)
{
cust.DoSumthing();
}
You should implement the class Customer so when calling method DoSumthing() on its objects it will only do something for the object which have index 4 in the for loop.
Ugly indexing is normally not needed in my experience.
/Patric
My C# blog: C# Coach
|
|
|
|
|
Patric_J wrote:
Ugly indexing is normally not needed in my experience.
I beg to differ. More often than not these days, I find myself writing stuff like this:
protected void DoSomething(MySortedStringList sortedElements, string[] buffer)
{
int i = 0;
foreach (string element in sortedElements)
{
buffer[i++] = element;
}
}
But that's what happens when having Hashtable as favourite collection
"God doesn't play dice" - Albert Einstein
"God not only plays dice, He sometimes throws the dices where they cannot be seen" - Niels Bohr
|
|
|
|
|
How do i get my textbox to accept the enter key as the same as clicking on the button? I want to beable to type then hit enter and when i hit enter it processes my request.
|
|
|
|
|
Try this
private void OnKeyPress(object sebnder, KeyPressEventArgs e)
{
if(e.KeyChar == (char) 13)
{
//Do Whatever you want }
else
{
base.OnKeyPress (e);
}
}
Live Life King Size
Alomgir Miah
|
|
|
|
|
Thanks....
|
|
|
|
|
The Form control has a property named AcceptButton. Set this to reference your button. In the same breath: You can also connect a button to the ESC key by referencing it in Form.CancelButton.
A small example:
public class MyForm: Form
{
private Button button;
public MyForm()
{
button = new Button();
this.Controls.Add(button);
AcceptButton = button;
}
}
"God doesn't play dice" - Albert Einstein
"God not only plays dice, He sometimes throws the dices where they cannot be seen" - Niels Bohr
|
|
|
|
|
Dont double post. If you really really really think that you absolutely need to draw attention in two separate message boards, keep the question in one of them, and post a link to the question in the other.
---
b { font-weight: normal; }
|
|
|
|
|
For your information it was actually ment to be two different questions!!! one for asp and the other for plain C#
I've got separate questions for separate programs and they just happen to have the same question related to them. I asked in separate places since i knew the asp question would be properly ansered in the asp board and then the C# question would be better asked in the C# board.
So maybe you should be less trigger happy when jumping folks!!!
oh, and if you didn't notice i didn't post the same exact question in both places, i made them each slightly different
but thank you for your concern for those maintaining the disk space on the servers, I'm sure they apreciate you watching their backs. they probably sleep better knowing Guffa has their backs.
but thats ok, heres a for your hard work!
you're worse than the soup nazi!
|
|
|
|
|
Well, the title differs, and the short information "using C#" in the ASP.NET question. Other than the questions are exactly identical, including spelling errors... If you intended to post two different questions, you should have posted two different questions. Then you wouldn't have people like me jumping you.
(The "using C#" information was totally superflous, by the way. As this is a strictly browser related questiuon, it is totally irrelevant what server language you use.)
How dare you compare me to the soup nazi? That wimp!
---
b { font-weight: normal; }
|
|
|
|
|
I neesd to get data from ana Access 2003 database and show them in in a datagrid in C#.Anybody can show me any tutorial about that?
|
|
|
|
|
http://www.codeproject.com/cs/database/csharpaccessdb.asp
Live Life King Size
Alomgir Miah
|
|
|
|
|
Can somebody help me find a regex that will locate this " | " in a string? The complete string is below... I'm new to regex but if I use an expression like "[ | ]" it finds all "|" plus all the " " (spaces) separately. Like I stated I want " | " together.
| Day | Amount | Direction | 3 | 100 | West | 5 | 43 | North | 5 | 44 | North West | 7 | 54 | South | 2 | 5995 | East | | | | | | | | | | 54 | 35345 | | | 543 | North | 6 | | West
If my explanation doesnt make sense, I want the above string to eventually look like with the use of replace...
Day,Amount,Direction,3,100,West,5,43,North,5,44,North West,7,54,South,2,5995,East,,,,,,,,,,54,35345,,,543,North,6,,West
And then based on a number n , replace every n th "," with a ";"
/\ |_ E X E GG
|
|
|
|
|
Fair warning, I'm not a regexp guru and while I have used them in textpad haven't used the c# regexp class, so I don't know the details of how it escapes things (tp supports 2 different rulesets so the standard isn't as tight as it could be). That said: IIRC | is a regexp control char that needs escaped, try escaping it with a \, also the [] construct's used to pick any of the chars inside of it not to define a substring. Try this instead: ( \| )
|
|
|
|
|
For your problem you it might be easier to use string.Split to get all values back and loop thru returned array to set values to either , or ;
string[] values = text.Split(new char[]{'|'});<br />
StringBuilder result = new StringBuilders();<br />
for (int i=0; i<values.Length; i++)<br />
{<br />
if (i > 0)<br />
{<br />
if (i == 3 || i == 5)<br />
sb.Append(';');<br />
else<br />
sb.Append(',');<br />
}<br />
<br />
sb.Append(values[i]);<br />
}<br />
<br />
return sb.ToString();
this will replace 3rd and 5th | with ; and all other with ,
|
|
|
|
|
Base
-------------------------
| public int iNo; |
| |
-------------------------
Class1 : Base Class2 : Base
---------------------------- --------------------------
| Class2 c2; | | private int iMyNo; |
| void Class1() | | public void SetMyNo()|
| { iNo = 10; | | { iMyNo = iNo; |
| c2 = new Class2(); | | } |
| c2.SetMyNo(); | --------------------------
| } |
----------------------------
This is my srtucture, I begin with Class1, which then init Base, and then sets iNo = 10. Next I create a new instance of Class2, which in turn again init Base. Now when I call c2.SetMyNo, it sets is to nothing, since there are two instances of Base. So how do I inherit Class2 from the same instance of Base, the super class of Class1?
There's someone in my head but it's not me - Pink Floyd
gunigugu
|
|
|
|
|
Your question is not very clear but if I understand it you have to two classes Class1 and Class2 both inheriting from Base.
Then you create two objects, c1 from Class1 and c2 from Class2. Both objects will have its own copy of the iNo, inhereted from Base. They are not the same iNo int variable just because they are defined in the same class, instead they refer to seperate variables in memory. You don't want to use inheritance in this case, you want to use aggregation
class Base
{
public int iNo;
}
class Class1
{
public Base myBase;
}
class Class2
{
public Base myBase;
}
class Test
{
[STAThread]
static void Main()
{
Base b = new Base();
b.iNo = 10;
Class1 c1 = new Class1();
c1.myBase = b;
Class2 c2 = new Class2();
c2.myBase = b;
Console.WriteLine("c1.myBase.iNo = " + c1.myBase.iNo);
Console.WriteLine("c2.myBase.iNo = " + c2.myBase.iNo);
c2.myBase.iNo = 5;
Console.WriteLine("c1.myBase.iNo = " + c1.myBase.iNo);
Console.WriteLine("c2.myBase.iNo = " + c2.myBase.iNo);
}
}
This will result in the following outpu
c1.myBase.iNo = 10
c2.myBase.iNo = 10
c1.myBase.iNo = 5
c2.myBase.iNo = 5
/Patric
My C# blog: C# Coach
|
|
|
|
|
Thank you very much, however I think I'm going to use static variables.
I'm quite new to programming and didn't know exactly how to work with static variables, so it didn't occurr to me.
Regards
There is someone in my head but it's not me - Pink Floyd
|
|
|
|
|
in this program there is a function to create a new desktop, and it includes the source, but it is in C++ and VB. is there a wway to create a new desktop in C#? If so, how? thanks
http://www.codeproject.com/win32/AntonioWinLock.asp
|
|
|
|
|