C sharp
Basics
Section titled Basics- 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:
null!
: the “null-forgiving” operator (reference). Use it when you know that an expression can’t benull
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 usingnull!
:[Export]private Sprite2D _bullet = null!;- The equivalent of Java’s
IllegalStateException
isSystem.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);
Events
Section titled EventsSimple 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 */;