Share via

Show me a usecase example code of asp.net, windows forms, unit tests and GoF

Gurdeep Vaidya 0 Reputation points
2026-04-29T22:15:42.5833333+00:00

need practical code examples covering the following C# topics:

  1. ASP.NET Core MVC – a simple use case, e.g. a controller returning data to a view
  2. Windows Forms – a basic example, e.g. button click event or form validation
  3. Unit Tests – a simple test using MSTest or NUnit
  4. GoF Design Patterns – a short example of any commonly used pattern (e.g. Singleton, Factory, Observer, Decorator)

Any minimal working code snippets would be greatly appreciated!

Developer technologies | C#
Developer technologies | C#

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.


2 answers

Sort by: Most helpful
  1. Jack Dang (WICLOUD CORPORATION) 17,585 Reputation points Microsoft External Staff Moderator
    2026-04-30T04:14:32.35+00:00

    Hi @Gurdeep Vaidya ,

    Thanks for reaching out.

    You can use the following small examples as a starting point. They are kept intentionally simple, but each one shows a practical pattern you would use in a real C# application.

    For an ASP.NET Core MVC example, you could have a controller prepare some data and pass it to a Razor view like this:

    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; } = string.Empty;
        public decimal Price { get; set; }
    }
    
    using Microsoft.AspNetCore.Mvc;
    
    public class ProductsController : Controller
    {
        public IActionResult Index()
        {
            var products = new List<Product>
            {
                new Product { Id = 1, Name = "Keyboard", Price = 49.99m },
                new Product { Id = 2, Name = "Mouse", Price = 19.99m }
            };
    
            return View(products);
        }
    }
    

    Then the Razor view can receive that model and display it:

    @model List<Product>
    
    <h2>Products</h2>
    
    <table>
        <thead>
            <tr>
                <th>Name</th>
                <th>Price</th>
            </tr>
        </thead>
        <tbody>
        @foreach (var product in Model)
        {
            <tr>
                <td>@product.Name</td>
                <td>@product.Price.ToString("C")</td>
            </tr>
        }
        </tbody>
    </table>
    

    In this case, when the user browses to /Products, the Index() action creates a small product list and passes it to the view for rendering.

    For Windows Forms, a common basic example is handling a button click and validating user input before showing a result:

    using System;
    using System.Windows.Forms;
    
    public class MainForm : Form
    {
        private readonly TextBox nameTextBox;
        private readonly Button submitButton;
        private readonly Label resultLabel;
    
        public MainForm()
        {
            Text = "Windows Forms Example";
            Width = 350;
            Height = 200;
    
            nameTextBox = new TextBox
            {
                Left = 20,
                Top = 20,
                Width = 200
            };
    
            submitButton = new Button
            {
                Left = 20,
                Top = 60,
                Width = 100,
                Text = "Submit"
            };
    
            resultLabel = new Label
            {
                Left = 20,
                Top = 100,
                Width = 300
            };
    
            submitButton.Click += SubmitButton_Click;
    
            Controls.Add(nameTextBox);
            Controls.Add(submitButton);
            Controls.Add(resultLabel);
        }
    
        private void SubmitButton_Click(object? sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(nameTextBox.Text))
            {
                MessageBox.Show("Please enter your name.");
                return;
            }
    
            resultLabel.Text = $"Hello, {nameTextBox.Text}!";
        }
    }
    

    The application entry point would look like this:

    using System;
    using System.Windows.Forms;
    
    internal static class Program
    {
        [STAThread]
        private static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MainForm());
        }
    }
    

    This creates a simple form with a textbox, a button, and a label. When the button is clicked, the code checks whether the textbox has a value before updating the label.

    For unit testing, here is a small MSTest example. First, this is the class being tested:

    public class Calculator
    {
        public int Add(int a, int b)
        {
            return a + b;
        }
    }
    

    And this is a matching test class:

    using Microsoft.VisualStudio.TestTools.UnitTesting;
    
    [TestClass]
    public class CalculatorTests
    {
        [TestMethod]
        public void Add_WhenCalled_ReturnsSum()
        {
            var calculator = new Calculator();
    
            int result = calculator.Add(2, 3);
    
            Assert.AreEqual(5, result);
        }
    }
    

    If you are using MSTest, make sure the test project has the usual test packages installed, for example:

    <PackageReference Include="MSTest.TestFramework" Version="3.4.3" />
    <PackageReference Include="MSTest.TestAdapter" Version="3.4.3" />
    <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.10.0" />
    

    For a GoF design pattern, a simple and useful one is the Factory pattern. It helps you create objects without spreading new SomeConcreteClass() throughout the application:

    public interface INotificationSender
    {
        void Send(string message);
    }
    
    public class EmailNotificationSender : INotificationSender
    {
        public void Send(string message)
        {
            Console.WriteLine($"Email sent: {message}");
        }
    }
    
    public class SmsNotificationSender : INotificationSender
    {
        public void Send(string message)
        {
            Console.WriteLine($"SMS sent: {message}");
        }
    }
    
    public static class NotificationSenderFactory
    {
        public static INotificationSender Create(string type)
        {
            return type.ToLower() switch
            {
                "email" => new EmailNotificationSender(),
                "sms" => new SmsNotificationSender(),
                _ => throw new ArgumentException("Unknown notification type")
            };
        }
    }
    

    You can then use it like this:

    INotificationSender sender = NotificationSenderFactory.Create("email");
    sender.Send("Your order has been shipped.");
    

    The benefit here is that the calling code works with the INotificationSender interface instead of depending directly on a specific implementation such as EmailNotificationSender or SmsNotificationSender. That makes the code easier to extend later if you add another sender type.

    Hope this helps! If my answer was helpful, I would greatly appreciate it if you could follow the instructions here so others with the same problem can benefit as well.


  2. Q&A Assist
    2026-04-29T22:15:59.0133333+00:00
    AI generated content. This question contains an answer created with AI from Q&A Assist. Learn more

    ASP.NET Core MVC, Windows Forms, unit tests, and GoF patterns can be illustrated with small, focused snippets.

    1. ASP.NET Core MVC – simple controller returning data to a view

    // Models/Product.cs
    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; } = string.Empty;
    }
    
    // Controllers/ProductsController.cs
    using Microsoft.AspNetCore.Mvc;
    using System.Collections.Generic;
    
    public class ProductsController : Controller
    {
        // GET: /Products
        public IActionResult Index()
        {
            var products = new List<Product>
            {
                new Product { Id = 1, Name = "Keyboard" },
                new Product { Id = 2, Name = "Mouse" }
            };
    
            return View(products); // passes the list to the view
        }
    }
    
    @* Views/Products/Index.cshtml *@
    @model IEnumerable<Product>
    
    <h2>Products</h2>
    <ul>
    @foreach (var p in Model)
    {
        <li>@p.Id - @p.Name</li>
    }
    </ul>
    

    This follows the guidance that most logic should live in services or models and controllers stay thin, which makes them easy to test with controller tests or functional tests.

    2. Windows Forms – button click event

    // Form1.cs
    using System;
    using System.Windows.Forms;
    
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
    
        private void buttonGreet_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(textBoxName.Text))
            {
                MessageBox.Show("Please enter your name.", "Validation",
                    MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
    
            MessageBox.Show($"Hello, {textBoxName.Text}!", "Greeting");
        }
    }
    

    Designer wiring (auto-generated when double-clicking the button in the designer):

    // Form1.Designer.cs (excerpt)
    private void InitializeComponent()
    {
        this.buttonGreet = new System.Windows.Forms.Button();
        this.textBoxName = new System.Windows.Forms.TextBox();
        // ... set properties, locations, etc.
        this.buttonGreet.Click += new System.EventHandler(this.buttonGreet_Click);
    }
    
    private System.Windows.Forms.Button buttonGreet;
    private System.Windows.Forms.TextBox textBoxName;
    

    3. Unit tests – xUnit example

    // Production code
    public class Calculator
    {
        public int Add(int a, int b) => a + b;
    }
    
    // CalculatorTests.cs
    using Xunit;
    
    public class CalculatorTests
    {
        [Fact]
        public void Add_TwoNumbers_ReturnsSum()
        {
            // Arrange
            var calculator = new Calculator();
    
            // Act
            var actual = calculator.Add(2, 3);
    
            // Assert
            Assert.Equal(5, actual);
        }
    
        [Theory]
        [InlineData(-1, 1, 0)]
        [InlineData(0, 0, 0)]
        [InlineData(10, 5, 15)]
        public void Add_VariousInputs_ReturnsExpected(int a, int b, int expected)
        {
            var calculator = new Calculator();
    
            var actual = calculator.Add(a, b);
    
            Assert.Equal(expected, actual);
        }
    }
    

    The [Fact] attribute marks a single test, while [Theory] with [InlineData] allows testing multiple input combinations with one test method.

    4. GoF Design Pattern – Singleton and Factory examples

    Singleton pattern

    public sealed class AppConfig
    {
        private static readonly Lazy<AppConfig> _instance =
            new Lazy<AppConfig>(() => new AppConfig());
    
        public static AppConfig Instance => _instance.Value;
    
        // Example configuration property
        public string ApplicationName { get; private set; }
    
        private AppConfig()
        {
            ApplicationName = "My Sample App";
        }
    }
    
    // Usage
    var name = AppConfig.Instance.ApplicationName;
    

    Factory pattern

    public interface INotification
    {
        void Send(string message);
    }
    
    public class EmailNotification : INotification
    {
        public void Send(string message)
        {
            Console.WriteLine($"Email: {message}");
        }
    }
    
    public class SmsNotification : INotification
    {
        public void Send(string message)
        {
            Console.WriteLine($"SMS: {message}");
        }
    }
    
    public static class NotificationFactory
    {
        public static INotification Create(string channel)
        {
            return channel switch
            {
                "email" => new EmailNotification(),
                "sms"   => new SmsNotification(),
                _       => throw new ArgumentException("Unknown channel", nameof(channel))
            };
        }
    }
    
    // Usage
    INotification notifier = NotificationFactory.Create("email");
    notifier.Send("Hello from factory pattern!");
    

    These snippets can be dropped into small projects (ASP.NET Core Web App, Windows Forms App, xUnit Test Project, and a class library/console app) to see them running end-to-end.


    References:

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.