IDumpable Interface in C#

In this article, we will discuss how to implement the IDumpable interface in C#. The IDumpable interface is a simple interface with a Dump() method and public properties. Those classes want to implement the IDumpable interface; they must implement the Dump() method and can use the interface's public properties to manage code execution.

Purpose of IDumpable:

The primary purpose of the IDumpable Interface is to apply contracts to objects that use the Dump method. By using the Dump method, the object's internal state can be captured and interpreted by humans. After that, this string is returned as an output. It is especially useful for debugging, logging, or other situations where we need to understand the contents of an object without investigating its internal structure.

Real-Time Example:

Let us take a real-time example to illustrate the IDumpable Interface in C#. Suppose we are driving a car and want to issue a command to know whether the car should run on petrol/diesel/CNG/electricity. Here, we use the Dump() method to determine the command to drive the car based on the command. Commands are issued through public interface properties at run time. First, define enumeration types for the various commands, and then DriveCommand enumeration defines four commands to drive the car.

Syntax:

It has the following syntax:

The next step involves creating an IDumpable interface that includes a Dump() method and corresponding public property of the type Command, which is named with the DriveCmd enum.

Example:

Let us take an example to illustrate the IDumpable Interface in C#.

Output:

I AM DRIVING THE BMW
Cmd : Using_PETROL
BMW CURRENTLY RUNS WITH Using_PETROL AT A SPEED OF 90 KM/HR

I AM DRIVING THE BMW
Cmd : Using_DIESEL
BMW IS NOT SUITABLE TO DRIVE ON Using_DIESEL

I AM DRIVING THE TRACTOR
Cmd : Using_DIESEL
TRACTOR CURRENTLY RUNS WITH Using_DIESEL WITH A SPEED OF 100 KM/HR

I AM DRIVING THE TUCSON
Cmd : Using_PETROLTUCSON CURRENTLY RUNS WITH Using_PETROL WITH SPEED OF 80 KM/HR

I AM DRIVING The TUCSON
Cmd : Using_ELECTRIC
TUCSON CURRENTLY RUNS WITH Using_ELECTRIC WITH SPEED OF 80 KM/HR

I AM DRIVING WAGONR
Cmd : Using_CNG
WAGONR CURRENTLY RUNS WITH Using_CNG WITH SPEED OF 50 KM/HR





Latest Courses