<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Josh Quezada</title>
    <description>The latest articles on DEV Community by Josh Quezada (@josh_dev).</description>
    <link>https://dev.to/josh_dev</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1920820%2F0c03385f-8956-4991-805e-8365cd4f0402.jpg</url>
      <title>DEV Community: Josh Quezada</title>
      <link>https://dev.to/josh_dev</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/josh_dev"/>
    <language>en</language>
    <item>
      <title>Developing an app using CQRS and Mediator pattern.</title>
      <dc:creator>Josh Quezada</dc:creator>
      <pubDate>Thu, 27 Mar 2025 00:50:15 +0000</pubDate>
      <link>https://dev.to/josh_dev/developing-an-app-using-cqrs-and-mediator-pattern-2dj8</link>
      <guid>https://dev.to/josh_dev/developing-an-app-using-cqrs-and-mediator-pattern-2dj8</guid>
      <description>&lt;h2&gt;
  
  
  What is CQRS!?
&lt;/h2&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;CQRS&lt;/strong&gt; for the acronyms of &lt;code&gt;Command Query Responsibility Segregation&lt;/code&gt; is a design pattern that segregates read and write operations for a data store into separate data models. &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;That is what Microsoft can tell us on their &lt;a href="https://learn.microsoft.com/en-us/azure/architecture/patterns/cqrs" rel="noopener noreferrer"&gt;documentation&lt;/a&gt;. As it says you'll take all the queries (GET requests) in one place and all the commands (POST, PUT, DELETE requests) in another place BUT not randomly (There's a lot of places where you can find more deep information but I took this as a simple base for what we'll made).&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvebpz5edhwe9fmgs76gt.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvebpz5edhwe9fmgs76gt.png" alt="SeparationRepresentation" width="800" height="261"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Why separate queries from commands? It's a question I've asked myself. Well, this is because the more complex your application is, the more complex it will be to maintain CRUD. When you have multiple layers of information in your application or simply add new features, you may need more resources or this may become a challenge.&lt;br&gt;
CQRS helps us with latency, throughput, or consistency issues. The use of CQRS is closely linked to &lt;code&gt;Event Sourcing&lt;/code&gt; and &lt;code&gt;DDD (Domain Driven Design)&lt;/code&gt; but this is something we will not discuss in this article.&lt;/p&gt;

&lt;p&gt;If we were to look for advantages of using CQRS in our application, we could summarize it as &lt;u&gt;scalability independently&lt;/u&gt;. &lt;/p&gt;
&lt;h2&gt;
  
  
  How does Mediator pattern fits?
&lt;/h2&gt;

&lt;p&gt;I like using real-life examples so let's look at one... People know how to buy food, is kind of simple: just go to the place you want and buy it. It's really simple, right? Yeah! but, what if you don't want to go? There's when you need a mediator to go for you and this mediator can go and buy for other people too without you talking to them, and then buy the food and gets your and other people food. In fact, there comes the idea of ​​an app where you can buy food at home (cof cof &lt;strong&gt;uber eats&lt;/strong&gt; cof cof)&lt;br&gt;
Mediator pattern is exactly the same! One of my favorites places to learn about patterns is &lt;a href="https://refactoring.guru/design-patterns/mediator" rel="noopener noreferrer"&gt;Refactoring Guru&lt;/a&gt; so, you can go and learn a lot of this pattern with detail there.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;The Mediator pattern suggests that you should cease all direct communication between the components which you want to make independent of each other.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;I like the mediator pattern because it follows the &lt;u&gt;Single Responsibility Principle&lt;/u&gt; extracting communication of multiple components and putting them into one single place and &lt;u&gt;Open/Close principle&lt;/u&gt; introducing new components without touching actual components.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fw4r38dcuvmuit5yekiga.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fw4r38dcuvmuit5yekiga.png" alt="MediatorRepresentation" width="800" height="291"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;See in previous image how both services uses the same mediator without knowing each other but both of them know the mediator to make calls and get information. Can you see now how CQRS and mediator are related? Imagine that &lt;code&gt;handler 1&lt;/code&gt; is a query and &lt;code&gt;handler 2&lt;/code&gt; is a command, there you have a relation between them.&lt;/p&gt;
&lt;h2&gt;
  
  
  Something you must have in mind...
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Mediator pattern must NOT be used in tiny applications like microservices because those applications are expected not to grow and be complicated to maintain.&lt;/li&gt;
&lt;li&gt;You should use it when your applications are growing too large and it becomes difficult to know where a component should be called or used and where it should not be used.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;
  
  
  Implementation of Database (Using .NET 8)
&lt;/h2&gt;

&lt;p&gt;I'll create an app where you can login as user and subscribe to be able of watch movies and series (I'm not going to create the video player, but the idea is to create the interface and access information about movies and series).&lt;br&gt;
Create an &lt;code&gt;ASP.NET Core Web API&lt;/code&gt; configured for &lt;em&gt;HTTPS&lt;/em&gt;, &lt;em&gt;OpenAPI Support Enabled&lt;/em&gt; and using &lt;em&gt;Controllers&lt;/em&gt;. The idea here is to create a real application that can scale and properly use these elements. I called my app as &lt;code&gt;CinemaWatcher&lt;/code&gt; and called my web api project as &lt;code&gt;CinemaWatcher.API&lt;/code&gt;.&lt;br&gt;
 &lt;u&gt;Delete all the default classes of weather, they won't be needed.&lt;/u&gt;&lt;/p&gt;

&lt;p&gt;After creating your web application add a Class Library and call it as you want. I called as &lt;code&gt;CinemaWatcher.Infrastructure&lt;/code&gt; this following the clean architecture structure. &lt;br&gt;
&lt;em&gt;Add a reference on our WebAPI project to our library.&lt;/em&gt;&lt;br&gt;
Then create a &lt;u&gt;DataAccess&lt;/u&gt; folder and create a folder for our entities with the name of &lt;code&gt;EntitiesModels&lt;/code&gt;.&lt;br&gt;
So we would have something like this:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;CinemaWatcher&lt;br&gt;
├ CinemaWatcher.API&lt;br&gt;
├── Controllers []&lt;br&gt;
├── appsettings.json&lt;br&gt;
├── Program.cs&lt;br&gt;
├ CinemaWatcher.Infrastructure&lt;br&gt;
├── DataAccess[]&lt;br&gt;
├── EntitiesModels []&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;NOTE:&lt;/em&gt;&lt;/strong&gt;&lt;br&gt;
Install by the NuGet packager the next packages:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Microsoft.EntityFrameworkCore (V 9.0.3)[Both projects]&lt;/li&gt;
&lt;li&gt;Microsoft.EntityFrameworkCore.SqlServer (V 9.0.3)[Only on Infrastructure]&lt;/li&gt;
&lt;li&gt;Microsoft.EntityFrameworkCore.Tools (V 9.0.3)[Both projects]&lt;/li&gt;
&lt;li&gt;MediatR (V 12.4.1)[Both projects]&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Let's continue and create three classes inside the Entities folder, one for &lt;code&gt;Users&lt;/code&gt;, &lt;code&gt;Movies&lt;/code&gt; and &lt;code&gt;Series&lt;/code&gt; which will be our main entities for now.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class User
{
    [Required]
    public int UserId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public string Password { get; set; }
    public string UserName { get; set; }
    public int Age { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class Series
{
    [Required]
    public int SerieId { get; set; }
    public string Title { get; set; }
    public string Category { get; set; }
    public string Duration { get; set; }
    public DateTime DateOfPublish { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class Movies
{
    public int MovieId { get; set; }
    public string Title { get; set; }
    public string Category { get; set; }
    public string Duration { get; set; }
    public DateTime DateOfPublish { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As you see there is nothing fancy now, just basic stuff. Add a class on our DataAccess folder called &lt;code&gt;AppDbContext&lt;/code&gt;. We created our entities, so to add them just add next code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    public class MyAppDbContext : DbContext
    {
        public MyAppDbContext(DbContextOptions&amp;lt;MyAppDbContext&amp;gt; options) : base(options)
        { }

        public DbSet&amp;lt;Movies&amp;gt; Movies =&amp;gt; Set&amp;lt;Movies&amp;gt;();
        public DbSet&amp;lt;Series&amp;gt; Series =&amp;gt; Set&amp;lt;Series&amp;gt;();


        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity&amp;lt;Movies&amp;gt;(builder =&amp;gt;
            {
                builder.HasKey(p =&amp;gt; p.MovieId);
                builder.Property(p =&amp;gt; p.Title).IsRequired().HasMaxLength(200);
                builder.Property(p =&amp;gt; p.Category).IsRequired().HasMaxLength(200);
                builder.Property(p =&amp;gt; p.Duration);
                builder.Property(p =&amp;gt; p.DateOfPublish);
            });

            modelBuilder.Entity&amp;lt;Series&amp;gt;(builder =&amp;gt;
            {
                builder.HasKey(p =&amp;gt; p.SerieId);
                builder.Property(p =&amp;gt; p.Title).IsRequired().HasMaxLength(200);
                builder.Property(p =&amp;gt; p.Category).IsRequired().HasMaxLength(200);
                builder.Property(p =&amp;gt; p.Duration);
                builder.Property(p =&amp;gt; p.DateOfPublish);
            });

            modelBuilder.Entity&amp;lt;User&amp;gt;(builder =&amp;gt;
            {
                builder.HasKey(p =&amp;gt; p.UserId);
                builder.Property(p =&amp;gt; p.FirstName).IsRequired().HasMaxLength(100);
                builder.Property(p =&amp;gt; p.LastName).IsRequired().HasMaxLength(100);
                builder.Property(p =&amp;gt; p.Email).IsRequired().HasMaxLength(200);
                builder.Property(p =&amp;gt; p.Password).IsRequired().HasMaxLength(10);
                builder.Property(p =&amp;gt; p.UserName).IsRequired().HasMaxLength(100);
                builder.Property(p =&amp;gt; p.Age);
            });
        }
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this app we'll use migrations, that's why you can see that we setup the entities using a builder. To create our DB let's go to our Program.cs class in our WebApi project and add next lines:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;builder.Services.AddDbContext&amp;lt;MyAppDbContext&amp;gt;(options =&amp;gt;
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"))
);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then on out &lt;code&gt;appsettings.Develpoment.json&lt;/code&gt; let's add that DefaultConnection:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  "ConnectionStrings": {
    "DefaultConnection": "YourConnectionStringFromSQLServer"
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then open you package Manager Console and run the next command:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;dotnet ef migrations add FirstMigrationDBCreation --startup-project WebApiRoute --project ClassLibraryRoute
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After that you may see that you have a new folder called "Migrations", to finalize the DB creation, run next command to apply the migration:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;dotnet ef database update --startup-project WebApiRoute --project ClassLibraryRoute
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Implementation of Mediator and CQRS (Using MediatR)
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;NOTE:&lt;/em&gt;&lt;/strong&gt;&lt;br&gt;
In previous versions of MediatR, the class library used to setup &lt;code&gt;MediatR.Extensions.Microsoft.DependencyInjection&lt;/code&gt; but in MediatR version 12 they improve the extension and is not necessary to install DependencyInjection.&lt;/p&gt;

&lt;p&gt;With the Database created we can go to implement the MediatR, to do that &lt;br&gt;
add the next line of code on our Program.cs:&lt;/p&gt;

&lt;p&gt;After setting up the MediatR add a new empty controller on the Controllers folder called &lt;u&gt;Movies&lt;/u&gt; and create a &lt;u&gt;Movies&lt;/u&gt; folder. On the Movies folder let's ad two more folders one of them will be &lt;code&gt;Queries&lt;/code&gt; and the other one will be &lt;code&gt;Commands&lt;/code&gt;.&lt;br&gt;
For now we'll just add a command handler to add movies, and a query handler to get all movies.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;CinemaWatcher&lt;br&gt;
├ CinemaWatcher.API&lt;br&gt;
├── Controllers []&lt;br&gt;
├──── MoviesController.cs&lt;br&gt;
├── Application[]&lt;br&gt;
├──── Movies[]&lt;br&gt;
├────── Queries []&lt;br&gt;
├──────── GetMoviesQuery.cs&lt;br&gt;
├────── Commands[]&lt;br&gt;
├──────── CreateMovieCommand.cs&lt;br&gt;
├── appsettings.json&lt;br&gt;
├── Program.cs&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Our GetMoviesQuery would look like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    public record GetMoviesQuery() : IRequest&amp;lt;List&amp;lt;Entities.EntitiesModels.Movies&amp;gt;&amp;gt;;

    public class GetMoviesQueryHandler : IRequestHandler&amp;lt;GetMoviesQuery, List&amp;lt;Entities.EntitiesModels.Movies&amp;gt;&amp;gt;
    {
        private readonly MyAppDbContext _context;
        public GetMoviesQueryHandler(MyAppDbContext context)
        {
            _context = context;
        }
        public async Task&amp;lt;List&amp;lt;Entities.EntitiesModels.Movies&amp;gt;&amp;gt; Handle(GetMoviesQuery request, CancellationToken cancellationToken)
        {
            return await _context.Movies.ToListAsync();
        }
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Our command would look like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    public record CreateMovieCommand(
        string Title,
        string Category,
        string Duration,
        DateTime DateOfPublish) :
        IRequest&amp;lt;Entities.EntitiesModels.Movies&amp;gt;;

    public class CreateMovieCommandHandler : IRequestHandler&amp;lt;CreateMovieCommand, Entities.EntitiesModels.Movies&amp;gt;
    {
        private readonly MyAppDbContext _context;
        private readonly IMediator _mediator;

        public CreateMovieCommandHandler(MyAppDbContext context, IMediator mediator)
        {
            _context = context;
            _mediator = mediator;
        }

        public async Task&amp;lt;Entities.EntitiesModels.Movies&amp;gt; Handle(CreateMovieCommand request, CancellationToken cancellationToken)
        {
            Entities.EntitiesModels.Movies newMovie = new()
            {
                Title = request.Title,
                Category = request.Category,
                Duration = request.Duration,
                DateOfPublish = request.DateOfPublish
            };
            _context.Movies.Add(newMovie);
            await _context.SaveChangesAsync();
            return newMovie;
        }
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Notice that I decided to use a &lt;a href="https://learn-microsoft-com.translate.goog/en-us/dotnet/csharp/language-reference/builtin-types/record?_x_tr_sl=en&amp;amp;_x_tr_tl=es&amp;amp;_x_tr_hl=es&amp;amp;_x_tr_pto=tc" rel="noopener noreferrer"&gt;record&lt;/a&gt; for the information we are passing to the handler and what is going to be added to the data.&lt;/p&gt;

&lt;p&gt;Finally our controller have the call to those requests and those processes. How do we call them? is easy, in the constructor we need to call MediatR so, if we have a nice structure in our project with the respective names of process, MediatR will find them and use them:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    [Route("api/[controller]")]
    [ApiController]
    public class MoviesController : ControllerBase
    {
        private readonly IMediator _mediator;

        public MoviesController(MyAppDbContext context, IMediator mediator)
        {
            _mediator = mediator;
        }

        [HttpGet]
        [Route("api/movies")]
        public async Task&amp;lt;List&amp;lt;Movies&amp;gt;&amp;gt; GetMovies()
        {
            return await _mediator.Send(new GetMoviesQuery());
        }

        [HttpPost]
        [Route("api/movies")]
        public async Task&amp;lt;Entities.EntitiesModels.Movies&amp;gt; CreateMovie([FromBody] Entities.EntitiesModels.Movies movie)
        {
            var newMovie = new CreateMovieCommand(movie.Title, movie.Category, movie.Duration, movie.DateOfPublish);

            return await _mediator.Send(newMovie);
        }
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And that's it! Try running the application and see how swagger ui can handle trying to call the queries and commands.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxb5wstgpmbbc45mkiw4w.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxb5wstgpmbbc45mkiw4w.png" alt="SwaggerExample" width="800" height="314"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion! What did I learn from this lesson?
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;I learned how to create a project from scratch and setup the dependencies to add a migration and create the database.&lt;/li&gt;
&lt;li&gt;I configured the MediatR extension and we setup it.&lt;/li&gt;
&lt;li&gt;I configured CQRS.&lt;/li&gt;
&lt;li&gt;I learned to encapsulate each functionality of the independent components.&lt;/li&gt;
&lt;li&gt;I created queries and commands to handle our requests and with this we can take a path to solve issues for events that can happen in our application.&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;NOTE:&lt;br&gt;
To go to the GitHub repository click &lt;a href="https://github.com/JoshQz/CinemaWatcherProject" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;In next lessons we'll review some of the topics that could be on the air like DDD, Events, Authentication, etc.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Hope this can help you and please let me know if I can improve something in my articles &amp;lt;3&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

</description>
      <category>backend</category>
      <category>dotnet</category>
      <category>learning</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Pattern matching for everyone (Using in video games)</title>
      <dc:creator>Josh Quezada</dc:creator>
      <pubDate>Thu, 14 Nov 2024 16:13:08 +0000</pubDate>
      <link>https://dev.to/josh_dev/pattern-matching-for-all-usage-in-videogames-2kc6</link>
      <guid>https://dev.to/josh_dev/pattern-matching-for-all-usage-in-videogames-2kc6</guid>
      <description>&lt;p&gt;Today's tutorial is a pattern that in my opinion we as programmers use very commonly but sometimes we don't even stop to investigate what we are using or why we are using it (&lt;em&gt;Me included&lt;/em&gt;).&lt;/p&gt;

&lt;p&gt;Since I saw this pattern, I immediately thought it could be used in video games. Pattern Matching is based on verifying what type of information is being used to perform some action or some block of code using Boolean expressions such as if or switch.&lt;/p&gt;

&lt;p&gt;This patter allows you to use multiple operations but I'll leave official documentation for it &lt;a href="https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/functional/pattern-matching" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Anyway, in today's tutorial I will use an object, creating it, programming its movement, actions and of course, verifying the actions taken by the user to do something.&lt;/p&gt;

&lt;p&gt;1.First of all we'll use a "Windows Forms App". &lt;br&gt;
2.Secondly we won't create any object using ToolBox.&lt;br&gt;
3.Finally I'm using Visual Studio 2022 using C# 8.0.&lt;/p&gt;

&lt;p&gt;The file we are interested on is "Form1.cs" (you can change the name of the file if you want).&lt;br&gt;
I won't change anything about 'Form1()' method but I'll modify the 'InitializeCommponent()' later.&lt;/p&gt;

&lt;p&gt;We need to create initial positions and size of our game object at that file:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//Initial positions of the GameObject
private int x = 100;
private int y = 100;
//Size of the GameObject
private int objectSize = 50;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As I said I will not use any object from toolBox, so we need to draw the object, in this case I preferred to use a circle but the &lt;code&gt;Graphics&lt;/code&gt; allows you to create multiple objects:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//Draw object at cuttent position
private void OnPaint(object sender, PaintEventArgs e)
{
    using (var brush = new SolidBrush(Color.Green))
    {
        e.Graphics.FillEllipse(brush, x, y, objectSize, objectSize);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now we get into the pattern, we have the next code where is using the switch expression:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;private void OnKeyDown(Object sender, KeyEventArgs e)
{
    switch (e.KeyCode)
    {
        case Keys.Left:
            x -= 10;
            break;
        case Keys.Right:
            x += 10;
            break;
        case Keys.Up:
            y -= 10;
            break;
        case Keys.Down:
            y += 10;
            break;
    }

    //Redraw the object after moving
    this.Invalidate();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;&lt;code&gt;What is the Pattern matching doing here?&lt;/code&gt;&lt;br&gt;
 Simple, it verifies the key event  we programmed (in this case I decided to use the arrow keys but can be changed very easily) and depending of what we pressed is going to do, moving up, moving down, you can even program "z" direction, remember that game development base is mathematics.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;And finally we can go to "InitializeComponent()" method I mentioned before. &lt;br&gt;
-&amp;gt; Setting &lt;code&gt;DoubleBuffered&lt;/code&gt; to true gives us the perspective of an animation and helps reduce or avoid information flickering.&lt;br&gt;
-&amp;gt; We call our Paint method and our Key event method.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;private void InitializeComponent()
{
    this.DoubleBuffered = true;
    this.Paint += new PaintEventHandler(OnPaint);
    this.KeyDown += new KeyEventHandler(OnKeyDown);

    SuspendLayout();
    // 
    // Form1
    // 
    AutoScaleDimensions = new SizeF(7F, 15F);
    AutoScaleMode = AutoScaleMode.Font;
    BackColor = SystemColors.ButtonShadow;
    ClientSize = new Size(800, 450);
    Name = "Form1";
    Text = "PatternMatching";
    ResumeLayout(false);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And that's all! You programmed a movement for an object and you learned about the pattern matching.&lt;/p&gt;

&lt;h2&gt;
  
  
  In conclusion
&lt;/h2&gt;

&lt;p&gt;You can use the pattern matching using switch, if, or any change expression. As well this pattern contains other types of patterns that can be used depending on what you want to do (Positional Pattern, Logical Pattern, etc). Of course this pattern can be used on multiple types of apps, is not mandatory to use it on videogames.&lt;/p&gt;

&lt;p&gt;Remember this is just an example for everyone to understand and if you have something to add please let me know and grow together.&lt;/p&gt;

&lt;h2&gt;
  
  
  References
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/patterns" rel="noopener noreferrer"&gt;Official Documentation&lt;/a&gt;&lt;br&gt;
&lt;a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/switch-expression" rel="noopener noreferrer"&gt;Switch expression&lt;/a&gt;&lt;br&gt;
&lt;a href="https://learn.microsoft.com/es-es/dotnet/api/system.windows.forms.control.doublebuffered?view=windowsdesktop-8.0" rel="noopener noreferrer"&gt;DoubleBuffered&lt;/a&gt;&lt;/p&gt;

</description>
      <category>csharp</category>
      <category>gamedev</category>
      <category>tutorial</category>
      <category>learning</category>
    </item>
  </channel>
</rss>
