Skip to content

C sharp

  • 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).

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 */;