Skip to content

C# Tips Based on Homework

Rainer Stropek edited this page Oct 21, 2019 · 5 revisions

C# Tips

Introduction

This Wiki page contains tips based on student homework.

General Tips

  • 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 Class1 or IClass1.
  • In C#, class and members names should start with an uppercase letter (e.g. CombineFiles instead of combineFiles).
  • Instead of myString == "", use String.IsNullOrEmpty.
  • Instead of "", use String.Empty
  • Avoid for (int i = 0; i < myArray.Length; i++) { ... }, consider foreach (var item in myArray) { ... } in such cases.

LINQ

  • Avoid myCollection.Count() > 0, prefer myCollection.Any() instead (docs).

Design Guidelines

  • In general, your functions should...
  • 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 readonly keyword 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 of List<string> results = new List<string>();).
  • When using dependency injection, avoid static members in classes.

Error Handling

  • Use Console.Error.WriteLine(...) if you want to print error messages on the screen. It will use STDERR instead of STDOUT.
Clone this wiki locally