Skip to content

C sharp

  • C# is open-source. If you ever want to find the code behind a particular class, go to a page like this and click the “Source” link toward the top:
    • Pasted image 20240520141654.png
  • null!: the “null-forgiving” operator (reference). Use it when you know that an expression can’t be null but the compiler can’t tell. For example, in Godot, you can set some variables through the game engine itself, but C# won’t know that they’re set, so you would initialize the variable using null!:
    [Export]
    private Sprite2D _bullet = null!;
  • The equivalent of Java’s IllegalStateException is System.InvalidOperationException (reference).
  • Use a Stopwatch to keep track of how much time has elapsed:
    Stopwatch _stopWatch = new();
    _stopWatch.Start();
    // do something
    _stopWatch.Stop();
    TimeSpan ts = _stopWatch.Elapsed;
    string elapsedTime = string.Format("{0:00}:{1:00}.{2:00}", ts.Minutes, ts.Seconds, ts.Milliseconds / 10);

Simple example:

public class TargetLocationComponent()
{
public event EventHandler<EventArgs> ReachedTarget = null!;
// Events can only be emitted from the owning class
public void EmitReachedTarget()
{
ReachedTarget(this, EventArgs.Empty);
}
}
// From some other code, raise the event:
tlc.EmitReachedTarget();
// From some listener code, subscribe to the event:
TargetLocationComponent tlc = new();
tlc.ReachedTarget += (object sender, EventArgs args) => /* do something */;