Ad Dashboard C#

👤 Sharing: AI
```csharp
using System;
using System.Collections.Generic;

namespace AdDashboard
{
    // Represents a single advertisement's data
    public class Ad
    {
        public string AdName { get; set; }
        public int Impressions { get; set; }
        public int Clicks { get; set; }
        public double Spend { get; set; }

        // Calculate Click-Through Rate (CTR)
        public double CTR
        {
            get
            {
                if (Impressions == 0) return 0; // Avoid division by zero
                return (double)Clicks / Impressions * 100;
            }
        }

        // Calculate Cost Per Click (CPC)
        public double CPC
        {
            get
            {
                if (Clicks == 0) return 0; // Avoid division by zero
                return Spend / Clicks;
            }
        }

        public Ad(string adName, int impressions, int clicks, double spend)
        {
            AdName = adName;
            Impressions = impressions;
            Clicks = clicks;
            Spend = spend;
        }

        public override string ToString()
        {
            return $"Ad: {AdName}, Impressions: {Impressions}, Clicks: {Clicks}, Spend: ${Spend:F2}, CTR: {CTR:F2}%, CPC: ${CPC:F2}";
        }
    }

    // Represents the Ad Dashboard itself
    public class AdDashboard
    {
        private List<Ad> ads = new List<Ad>();

        // Add a new ad to the dashboard
        public void AddAd(Ad ad)
        {
            ads.Add(ad);
        }

        // Display all ads in the dashboard
        public void DisplayAds()
        {
            if (ads.Count == 0)
            {
                Console.WriteLine("No ads to display.");
                return;
            }

            Console.WriteLine("--- Ad Dashboard ---");
            foreach (var ad in ads)
            {
                Console.WriteLine(ad);
            }
            Console.WriteLine("----------------------");
        }

        // Calculate and display summary metrics for all ads
        public void DisplaySummary()
        {
            if (ads.Count == 0)
            {
                Console.WriteLine("No ads to display summary.");
                return;
            }

            int totalImpressions = 0;
            int totalClicks = 0;
            double totalSpend = 0;

            foreach (var ad in ads)
            {
                totalImpressions += ad.Impressions;
                totalClicks += ad.Clicks;
                totalSpend += ad.Spend;
            }

            double overallCTR = (totalImpressions == 0) ? 0 : (double)totalClicks / totalImpressions * 100;
            double overallCPC = (totalClicks == 0) ? 0 : totalSpend / totalClicks;


            Console.WriteLine("--- Ad Dashboard Summary ---");
            Console.WriteLine($"Total Impressions: {totalImpressions}");
            Console.WriteLine($"Total Clicks: {totalClicks}");
            Console.WriteLine($"Total Spend: ${totalSpend:F2}");
            Console.WriteLine($"Overall CTR: {overallCTR:F2}%");
            Console.WriteLine($"Overall CPC: ${overallCPC:F2}");
            Console.WriteLine("-----------------------------");

        }
    }

    // Main program entry point
    class Program
    {
        static void Main(string[] args)
        {
            // Create an AdDashboard instance
            AdDashboard dashboard = new AdDashboard();

            // Create some sample ads
            Ad ad1 = new Ad("Summer Sale Ad", 10000, 500, 50.00);
            Ad ad2 = new Ad("New Product Launch", 5000, 200, 30.00);
            Ad ad3 = new Ad("Brand Awareness Campaign", 20000, 1000, 100.00);

            // Add ads to the dashboard
            dashboard.AddAd(ad1);
            dashboard.AddAd(ad2);
            dashboard.AddAd(ad3);

            // Display the ads
            dashboard.DisplayAds();

            //Display the summary
            dashboard.DisplaySummary();
        }
    }
}
```

Key improvements and explanations:

* **Clearer Structure:** The code is now organized into classes: `Ad` and `AdDashboard`, making it more object-oriented and maintainable.
* **Ad Class:**
    * `AdName`: The name of the advertisement.
    * `Impressions`: The number of times the ad was shown.
    * `Clicks`: The number of times the ad was clicked.
    * `Spend`: The amount of money spent on the ad.
    * `CTR` (Click-Through Rate):  Calculated as (Clicks / Impressions) * 100.  Handles the case where `Impressions` is zero to prevent a `DivideByZeroException`.
    * `CPC` (Cost Per Click): Calculated as Spend / Clicks. Handles the case where `Clicks` is zero to prevent a `DivideByZeroException`.
    * `ToString()`: Overrides the default `ToString()` method to provide a user-friendly string representation of an `Ad` object.  Includes formatted currency and percentage values.
* **AdDashboard Class:**
    * `ads`: A `List<Ad>` to store the advertisements.
    * `AddAd(Ad ad)`:  Adds an `Ad` object to the `ads` list.
    * `DisplayAds()`: Iterates through the `ads` list and prints the details of each `Ad` using the `ToString()` method.  Also includes a check to handle an empty dashboard.
    * `DisplaySummary()`: Calculates and displays summary metrics: total impressions, total clicks, total spend, overall CTR, and overall CPC.  Includes checks for empty ads list and division by zero.  Uses formatted output for currency and percentages.
* **Main Program:**
    * Creates an `AdDashboard` instance.
    * Creates several `Ad` instances with sample data.
    * Adds the `Ad` instances to the `AdDashboard`.
    * Calls `DisplayAds()` to show the ad details.
    * Calls `DisplaySummary()` to show the summary statistics.
* **Error Handling (Division by Zero):**  The `CTR` and `CPC` properties, and the summary calculations, now include checks to prevent division by zero, which would cause an exception.  They return 0 in these cases. This makes the code more robust.
* **Formatting:** Uses `string.Format` (or string interpolation with `:F2`) to format currency values to two decimal places (e.g., `$50.00`) and percentage values to two decimal places (e.g., `2.50%`). This makes the output much more readable.
* **Clarity and Comments:**  Added comments to explain the purpose of each class, method, and property.  The code is also written with clear variable names.
* **Object-Oriented Approach:** The use of classes makes the code more modular, reusable, and easier to extend in the future.  For example, you could easily add new properties to the `Ad` class (e.g., target audience, geographical region) or new methods to the `AdDashboard` class (e.g., filter ads by CTR, generate reports).
* **Console Output:**  The output to the console is formatted for better readability.
* **Completeness:** This example now covers data storage, calculation of common metrics, and display of both individual ad details and overall summary statistics.

How to run:

1.  **Save:** Save the code as a `.cs` file (e.g., `AdDashboard.cs`).
2.  **Compile:** Open a command prompt or terminal and navigate to the directory where you saved the file.  Compile the code using the C# compiler:

    ```bash
    csc AdDashboard.cs
    ```

3.  **Run:** Execute the compiled program:

    ```bash
    AdDashboard.exe
    ```

The output will be displayed in the console, showing the details of each ad and the overall summary.
👁️ Viewed: 3

Comments