Creating an instance of a class (new) var calculator = new PriceCalculator(taxRate: 0.18m); var total = calculator.Calculate(1000m); Behind the scenes: 1. The runtime ensures the type is loaded and its static constructor (if any) has run. 2. Memory for the object is allocated on the managed heap: an object header, a pointer to the type's method table, and the instance fields. Allocation is fast (bumping a pointer in the current allocation context). 3. Fields are zero-initialised, then the constructor chain runs (base class constructors first). 4. A reference to the new object is stored in the variable (on the stack or in another object). 5. Calling an instance method passes a hidden "this" reference as the first argument. For non-virtual methods the call goes directly to the method's address; for virtual or interface methods the runtime looks up the implementation through the method table (virtual dispatch). 6. The object stays alive while it is reachable, and later the garbage collector reclaims it. Each instance has its own copy of instance fields, so two calculators can hold different tax rates. Calling a method on a static class by its name var total = TaxHelper.AddGst(1000m); Behind the scenes: 1. No object is created and no heap allocation happens for the call. 2. Static classes cannot be instantiated; they are abstract and sealed at the IL level. 3. The first time the type is used, the runtime runs its static initialisation (static field initialisers and the static constructor) exactly once per application domain or load context, in a thread-safe way. Static fields are stored once per type, not per instance. 4. The method is called directly by its address, with no "this" parameter and no virtual dispatch, so the call is slightly cheaper. 5. Static fields live for the lifetime of the application (until the type's load context is unloaded), so anything they reference is never garbage-collected. Practical implications - Instances can hold per-object state, implement interfaces, be replaced through dependency injection and mocked in tests. - Static members are global and shared: good for pure, stateless utilities (Math.Max, string helpers), but static mutable state is shared by all threads (needs synchronisation) and makes testing harder, and static dependencies cannot be swapped easily. - Performance differences are usually negligible; design and testability should drive the choice. - Extension methods are a common way to provide utility behaviour via static classes.
Ravindra Wadile · · 0 likes