-
Notifications
You must be signed in to change notification settings - Fork 62
C# Tips Based on Homework
Rainer Stropek edited this page Oct 21, 2019
·
5 revisions
This Wiki page contains tips based on student homework.
- Always format code before checking it in (docs). Consider installing the Code Cleanup on Save extension.
- Avoid checking in unnecessary code by generating and adding a .gitignore file in the root folder of your solution (avoid separate ones in all project folders).
- If you build multiple projects that logically belong to a single application, create a single solution with multiple projects (docs).
- Choose meaningful names, not names like
Class1orIClass1. - In C#, class and members names should start with an uppercase letter (e.g.
CombineFilesinstead ofcombineFiles). - Instead of
myString == "", useString.IsNullOrEmpty. - Instead of
"", useString.Empty - Avoid
for (int i = 0; i < myArray.Length; i++) { ... }, considerforeach (var item in myArray) { ... }in such cases.
- Avoid
myCollection.Count() > 0, prefermyCollection.Any()instead (docs).
- In general, your functions should...
- ...return the most specific type (e.g.
ICollectioninstead ofIEnumerable) and - ...accept the most generic type (e.g.
IEnumerableinstead ofList).
- ...return the most specific type (e.g.
- Avoid namespaces with too few types (e.g. namespace with just one interface).
- Make an object immutable if you do not need to change its state after it has been created. Do that be removing setters and/or using the
readonlykeyword for fields. Example:
// The following class is NOT immutable although W1 and W2 are not changed after object creation.
public class Anagram
{
public string W1 { get; set; }
public string W2 { get; set; }
public Anagram(string w1, string w2)
{
this.W1 = w1;
this.W2 = w2;
}
}
// This version of the class would be better. It is immutable.
public class AnagramImmutable
{
public string W1 { get; }
public string W2 { get; }
public Anagram(string w1, string w2)
{
this.W1 = w1;
this.W2 = w2;
}
}- If you get an error like Inconsistent accessibility: parameter type ... is less accessible than method ..., check this StackOverflow answer.
- When the type of a variable in an assignment is obvious, prefer
var(e.g.var results = new List<string>();instead ofList<string> results = new List<string>();). - When using dependency injection, avoid
staticmembers in classes.
- Use
Console.Error.WriteLine(...)if you want to print error messages on the screen. It will use STDERR instead of STDOUT.