String concatenation instead of StringBuilder
String concatenation works in such a way that every time when you add something to a string, a new address in the memory is being allocated. The previous string is copied to a new location with the newly added part. This is inefficient. On the other hand we have StringBuilder which keeps the same position in the memory without performing the copy operation.
- //INCORRECT
- List<string> values = new List<string> { "This ", "is ", "Abrar ", "!" };
- string outputValue = string.Empty;
- foreach (var value in values)
- {
- outputValue += value;
- }
- //CORRECT
- StringBuilder outputValueBuilder = new StringBuilder();
- foreach (var value in values)
- {
- outputValueBuilder.Append(value);
- }
A lot of programmers find a certain set of elements by means of ‘Where’ and then return the first occurrence. This is inappropriate, because the ‘First’ method can be also applied with the ‘Where’ condition. What’s more, it shouldn’t be taken for granted that the value will always be found. If “First” is used when no value is found, an exception will be thrown. Thus, it’s better to use FirstOrDefault instead. When using FirstOrDefault, if no value has been found, the default value for this type will be returned and no exception will be thrown.
- //INCORRECT
- List<int> numbers = new List<int> { 1, 4, 5, 6, 2, 3, 4, 5, 6, 3, 6, 23, 23 };
- return numbers.Where(x => x == 6).First();
- //PARTLY CORRECT
- return numbers.First(x =>x==6);
- //CORRECT
- return numbers.FirstOrDefault(x => x == 6);
- //INCORRECT
- var allIndiaEmployee =EmployeeList.OrderBy(x => x.EmployeeName)
- .Where(x => x.Country == Country.India);
- //CORRECT
- var allIndiaEmployee = EmployeeList.Where(x => x.Country == Country.India)
- .OrderBy(x => x.EmployeeName);

Join the conversation! Your thoughts help the community grow.