In the following examples:
- the first seems more verbose but less wasteful of resources
- the second is less verbose but more wasteful of resources (redefines string each loop)
Which is better coding practice?
First example:
using System;
using System.Collections.Generic;
namespace TestForeach23434
{
class Program
{
static void Main(string[] args)
{
List<string> names = new List<string> { "one", "two", "two", "three", "four", "four" };
string test1 = "";
string test2 = "";
string test3 = "";
foreach (var name in names)
{
test1 = name + "1";
test2 = name + "2";
test3 = name + "3";
Console.WriteLine("{0}, {1}, {2}", test1, test2, test3);
}
Console.ReadLine();
}
}
}
Second example:
using System;
using System.Collections.Generic;
namespace TestForeach23434
{
class Program
{
static void Main(string[] args)
{
List<string> names = new List<string> { "one", "two", "two", "three", "four", "four" };
foreach (var name in names)
{
string test1 = name + "1";
string test2 = name + "2";
string test3 = name + "3";
Console.WriteLine("{0}, {1}, {2}", test1, test2, test3);
}
Console.ReadLine();
}
}
}
Object a = new Object();
, it would be worse to do that in the loop, if I can create it once out of the loop and just modify the values in the loop - since if it was in the loop, objects are really being created and destroyed in the loop. – Intercontinental