Posts

Showing posts from June 19, 2025

Difference Between Dispose() and Finalize() in C#

Difference Between Dispose() and Finalize() in C# In C#, both Dispose() and Finalize() are used to release unmanaged resources (like file handles, database connections, or network sockets), but they differ in how and when they are used.   What is Dispose()? Part of the IDisposable interface. Must be called manually by the developer or via a using block. Releases unmanaged resources deterministically (i.e., at a known time). Ideal for cleaning up resources as soon as you're done with them. Commonly used with: Files, database connections, network streams.   What is Finalize()? A special method: ~ClassName() (destructor syntax in C#). Called automatically by the Garbage Collector (GC) . Runs non-deterministically —you don’t know exactly when. Typically used as a backup in case Dispose() wasn’t called. Note: You should avoid using Finalize() unless absolutely necessary because it can slow down garbag...

Difference Between Abstraction and Encapsulation in C#

Difference Between Abstraction and Encapsulation in C# Both Abstraction and Encapsulation are fundamental principles of Object-Oriented Programming (OOP). They may sound similar, but they address different concerns:   What is Abstraction? Abstraction is the process of hiding the implementation details and showing only the essential features of an object. It focuses on what an object does , rather than how it does it . Implemented using: Interfaces Abstract classes Example: public interface IPrinter {     void Print(); }   public class LaserPrinter : IPrinter {     public void Print()     {         // complex logic hidden         Console.WriteLine("Printing document...");     } } In this example, the interface abstracts the printing operation. The user only knows about Pr...

Difference Between Interface and Abstract Class in C#

Difference Between Interface and Abstract Class in C# In object-oriented programming with C#, both interfaces and abstract classes are used to achieve abstraction —a fundamental principle that hides implementation details and exposes only relevant functionality. However, they are used differently and serve different purposes.   What is an Interface? An interface defines a contract : what a class must do , but not how it does it. It contains only method signatures, properties, events, or indexers. No implementation is allowed (except default interface methods in C# 8.0+). A class can implement multiple interfaces . Example: public interface IAnimal {     void Speak(); }   What is an Abstract Class? An abstract class is a partially implemented class . It can contain both abstract members (without implementation) and concrete members (with implementation). Cannot be instantiat...