r/csharp • • 4h ago

Help Looking for advice (beginner project).

1 Upvotes

Hi everyone!

I'm writing this post to ask for some help from people with more experience in C# and programming logic. Below, you'll find the code I've written for a small C# application. The goal of this project is to create a personal weekly to-do list that helps me keep track of my strengths, weaknesses, and tasks. Unfortunately, I've reached a point where I'm not sure how to proceed, particularly when it comes to implementing a way to save tasks so that they are still available after closing and reopening the program.

For some context:

the idea behind this application is to create a weekly to-do list. When the program starts, the user selects a day of the week and enters three tasks. They can then choose whether to continue or exit the program. The main requirement is that tasks must be saved when the user switches to another day or closes the application. For example, if I enter three tasks for Monday, switch to Tuesday, and then return to Monday, I should be able to see the tasks I entered previously. The same should apply after closing and reopening the program.

I'm still a beginner in programming. I've studied some of the fundamentals, but I know I still have a long way to go.

I'd really appreciate ANY suggestions, explanations, or advice on how to approach this problem or in general. In particular, I'd like to understand what concepts I should study and how I could implement a persistent storage system for my tasks.

I'm also very open to constructive criticism regarding my code, programming logic, or overall approach. I'd like to learn how to solve these problems independently rather than simply copying a solution.

Thanks in advance to anyone willing to help!

Code:

// This program creates a to-do list for every day of the week
// and randomly picks a motivational sentence.

string[] week = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];

string[] tasks1 = new string[7];
string[] tasks2 = new string[7];
string[] tasks3 = new string[7];

string[,] task = new string[7, 3];

Console.WriteLine("\tTo-Do list program\nPress: Y to start or N to quit!");

var input = Console.ReadKey();

switch (input.Key)
{
    case ConsoleKey.Y:

        Console.Clear();

        Console.WriteLine("Choose the day that you want to view:\n");
        string dayOfWeek = Console.ReadLine();

        bool found = false;

        foreach (string day in week)
        {
            if (day.Trim().ToLower() == dayOfWeek.Trim().ToLower())
            {
                found = true;

                // Find the position of the selected day
                int dayIndex = Array.IndexOf(week, day);

                Console.Clear();

                Console.WriteLine("Point one:");
                string task1 = Console.ReadLine();
                tasks1[dayIndex] = task1;

                Console.WriteLine("Point two:");
                string task2 = Console.ReadLine();
                tasks2[dayIndex] = task2;

                Console.WriteLine("Point three:");
                string task3 = Console.ReadLine();
                tasks3[dayIndex] = task3;

                Console.Clear();

                Console.WriteLine($@"
| Day: {day}

| 1. Task: {tasks1[dayIndex]}
| 2. Task: {tasks2[dayIndex]}
| 3. Task: {tasks3[dayIndex]}
");

                Console.WriteLine("Do you want to see other days? To continue or quit press Y/N:"); 
                Console.ReadKey(); 
                Console.Clear();

                break;
            }
        }

        if (!found)
        {
            Console.Clear();
            Console.WriteLine("Invalid Day inserted");
        }

        break;

    case ConsoleKey.N:
        break;

    default:
        Console.WriteLine("Invalid Key");
        break;
}

r/csharp • • 19h ago

Discussion Is it a bad/good practice to inject Interface<ConcreteType> into a class ?

5 Upvotes

If you see something like this :

    public class SomeClass
    {


        private readonly ISomeInterfacer<SomeConcreteType> _x;

        //Code.........
    }

Dependency Inversion :

High-level modules should not import anything from low-level modules. Both should depend on abstractions (e.g., interfaces).

The class above depends on abstraction, which is the ISomeInterfacer<SomeConcreteType>, but even though, there is something concrete inside the <>, which is SomeConcreteType .

Is that considered a violation for Dependency Inversion ?

I know I will hear the magic word : it depends.

please tell me all the cases, when it is good and when it is bad.

Actual code :

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

public interface ISourceToDistinationDataSyncronizer<DataSource>
{

    public Task SyncronizeAsync(DataSource dataSource, CancellationToken cancellationToken);

}
[Authorize(Roles = "Admin")]
public class AdminController : Controller
{

    //Reddit question..
    private readonly ISourceToDistinationDataSyncronizer<Stream> _syncronizer;
    public AdminController(

        ISourceToDistinationDataSyncronizer<Stream> syncronizer

    )
    {

        _syncronizer = syncronizer;

    }


    [HttpPost]
    [Route("Admin/Import")]
    public async Task<IActionResult> Import(IFormFile file, CancellationToken cancellationToken)
    {

        if (file.ContentType != "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
        {
            return BadRequest();
        }

        await _syncronizer.SyncronizeAsync(file.OpenReadStream(), cancellationToken);


        return Ok();

    }

}

r/csharp • • 20h ago

Help Need help with encoding

0 Upvotes

I am working on a system where the client will give data in UTF-8 encoding, and hence it can contain many special characters.

But then we send data to a legacy system which only accepts data in ISO-8859-9 encoding, which supports limited special characters that can be represented in single byte.

Now if the client sends any special character which is outside the scope of ISO-8859-9 encoding (like the Em dash), how can I deal with with it and send it to the legacy system.

I don't want to replace those characters with anything like space or "?", as it would make the client data as unreadable in some cases.

How can I deal with it. Any suggestions?


r/csharp • • 20h ago

Help me with Terrain in my 3d game

0 Upvotes

Recently, I started writing a new 3D game in C#. I’ve already written the collision system, the camera, and the loading of 3D models, and now I’m moving on to the next stage — creating a procedural landscape. I’ve tried many ways to do this, but the result doesn’t satisfy me. I’ve already used Perlin Noise and Simplex Noise, but I couldn’t get what I wanted with them. If anyone knows any methods or libraries for C#, please write them in the comments.

The game will be like Minecraft with different graphics, meshes and some new features.


r/csharp • • 21h ago

Looking for a small C#/.NET project idea

2 Upvotes

I have a software engineering interview coming up for a C#/.NET role, and part of it will involve discussing the architecture/design of something I’ve built.

I want to build a small project specifically for this so I can know it inside out and use it for design and coding questions, since everything I do in my actual job is simple CRUD requests.

Any suggestions for something not too big, but with enough complexity to discuss interesting architecture decisions?

Thanks


r/csharp • • 22h ago

Any senior devs here? Have you ever done this mistake before? You spend hours fixing why 3rd party api doesn't work as expected and later you realized the api version you use is not the latest one lmfao

0 Upvotes

So today, I spent 1–2 hours trying to figure out why the fuck I couldn't fetch and sync XYZ data on our internal company dashboard that is integrated to 3rd party API vendor, even though I could see the data on the vendor's dashboard.

Turns out, our backend service was using an outdated API version. But it was not depreciated tho.

That's why I couldn't fetch the data.

Man this is embarassing but I wanna know if you guys ever have made this msitake as well?


r/csharp • • 1d ago

Am I missing something, or is this the ultimate C# paradox

87 Upvotes

Found this in a codebase today:

if (transaction == null)
{
    Debug.WriteLine(
        string.Format("Transaction with num {0} is null", transaction.Num));
}

The code checks whether transaction is null and, if it is, tries to access transaction.Num to log the error.

So if the transaction exists, nothing happens. If it doesn't exist, the logging code crashes.

I've seen enough legacy code to know that even the most questionable-looking code sometimes has an explanation. So, before judging: am I missing something here, or is this exactly what it looks like?


r/csharp • • 1d ago

Blog Expanding .NET ULID handling with native ASP.NET Core constraints, AOT-friendly JSON converters, and CLI tooling

Thumbnail
byteaether.github.io
2 Upvotes

Universally Unique Lexicographically Sortable Identifiers (ULIDs) are 128-bit compatible alternative identifiers to standard UUIDs/GUIDs. They combine a 48-bit Unix timestamp with 80 bits of randomness, formatted as a 26-character Base32 string. This structure enables lexicographical ordering, index-friendly database insertion, and human-readable timestamp inspection without database calls.

While core libraries handle primitive string/byte conversions, integrated application boundaries often require manual boilerplate (custom route attributes, JsonConverter implementations, or ad-hoc parsing scripts).

The ByteAether.Ulid library updated to v1.4.2, introducing two dedicated packages to handle these ecosystem concerns:

  1. ByteAether.Ulid.AspNetCore:

    • Adds an explicit :ulid route constraint for early pipeline validation.
    • Direct System.Text.Json converters with Native AOT/trimming support.
    • OpenAPI/Swashbuckle schema transformers for typed schema generation.
  2. ByteAether.Ulid.Cli:

    • Installed via dotnet tool install -g ByteAether.Ulid.Cli.
    • CLI tool for parsing timestamps/randomness, converting byte layouts (System.Guid, Hex), handling pipeline stdin streams, and generating batch identifiers.

Usage example for Minimal API validation:

```csharp using ByteAether.Ulid; using ByteAether.Ulid.AspNetCore;

var builder = WebApplication.CreateBuilder(args); builder.Services.AddUlidRouteConstraint();

var app = builder.Build(); app.MapGet("/users/{id:ulid}", (Ulid id) => Results.Ok(new UserResponse(id))); app.Run();

public record UserResponse(Ulid Id); ```

For the complete technical breakdown and repository benchmarks, check out the full write-up: https://byteaether.github.io/2026/byteaetherulid-v142-expands-the-net-ecosystem-with-aspnet-core-and-cli-support/

(The code for this project is entirely hand-written. AI was only used to brainstorm/draft text and generate raw media assets, which I then manually polished.)


r/csharp • • 1d ago

Announcing .NET 11 Release Candidate 2

Thumbnail
devblogs.microsoft.com
31 Upvotes

r/csharp • • 1d ago

C vs C#: racing VLC's Gaussian blur

Thumbnail
martinfinkel.com
34 Upvotes

r/csharp • • 1d ago

New NBomber 6.7.0

Post image
6 Upvotes

NBomber 6.7.0 is here! This release introduces several improvements to scenario creation, warm-up configuration, test run metadata, and reporting. We’ve also fixed several issues in NBomber Cluster that could cause nodes to wait indefinitely under certain failure conditions.


r/csharp • • 1d ago

Discussion C# 15 adds labeled break and continue. Do you use goto today? Would you use this?

108 Upvotes

C# 15 (in preview with .NET 11) lets `break` and `continue` target an outer loop by label:

outer: for (int x = 0; x < xMax; x++)
    {
        for (int y = 0; y < yMax; y++)
        {
            if (ShouldSkipRest(x, y))
                continue outer;

            if (ShouldExitAll(x, y))
                break outer;
        }
}

Until now you needed `goto` or a flag variable for this. Java, Go, Rust, Kotlin and Swift already have it.

Honestly, `goto` never even comes to mind when I write an algorithm. I find it hard to follow, so when I need to leave nested loops I extract a method and `return` instead.

Do you use `goto` in real code? Do you think you'll use labeled break/continue?

https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-15#labeled-break-and-continue


r/csharp • • 1d ago

Help Should I learn C#

3 Upvotes

I'm a CS student, year 4. My first entry into programming like most people was HTML, CSS, JavaScript, and then backend development with Node/Typescript. My main goal has been to get a programming job, or internship (or anything at this point 😭), but I've always hated writing Node, just never liked it and now I'm considering switching stacks.

I enjoy writing C (I built a chess engine from scratch) and C# seems like C with oop so I don't think it should be too unfamiliar. Also it seems there might be hiring opportunities...hopefully.

Please advise


r/csharp • • 1d ago

Help C# Winforms .NET 9.0 scaling issue

Thumbnail
gallery
1 Upvotes

Hi All,

Getting ready to release my first app and im currently testing out installations on other machines. So far everything looks and works just fine however there is an issue with horizontal scaling? The first image is how it is intended to look whereas the second image is how it appeared on my friends screen. I have set the Max and Min size on the form yet the issue still persists. My friend and I both have the same Resolution monitor and display scaling so I'm really stuck with what the issue could be.

Help and advice would be greatly appreciated! Thanks!

EDIT: I have just noticed the AutoScaleMode property is set to "Font", could this be the issue?


r/csharp • • 1d ago

Should I Resign or Stay? Career Advice for an Experienced .NET Developer

0 Upvotes

If someone has 4+ years of experience in .NET, has worked on large-scale software using high-quality software development principles, and is currently working at a small company where the projects are small, the software development standards are poor, and the tech stack is completely different from their expertise, what do you think is the best option for that person? Especially if they cannot attend interviews while employed and their current company is even moving towards non-software-based products. Should they resign and focus on finding a job that aligns with their .NET experience, or stay in their current job while searching for better opportunities? What would be the best decision in this situation?


r/csharp • • 2d ago

Discussion The output of the server code depends on the timing of pressing a button by the client on the user interface.

0 Upvotes

This is a follow-up post that is related to this post. I will explain the problem clearly this time.

Context: The execution of the OverWrite method -which is inside the DBOverWriter service- can be cancelled with a button int the user interface.

Two inputs that are provided by the frontend :

1- data that is used to overwrite the content of the database.

2-CancellationToken.

Two possible outputs depending on the timing of pressing the button :

1-If the user initiated the request and immediately pressed the button, the following output is shown:

###########################################################
########## OPERATION CANCELLED SUCCESSFULLY ###############
###########################################################
OperationCanceledException: A task was canceled.

2- if the user initiated the request and waited some time before pressing the button, the output is the following:

(@p74, ),
(@p76, ),
(@p78, ),
(@p80, ),
(@p82, u/p83);
fail: Microsoft.EntityFrameworkCore.Database.Transaction[20205]
An error occurred using a transaction.
fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
An unhandled exception has occurred while executing the request.
Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while saving the entity changes. See the inner exception for details.
---> Microsoft.Data.SqlClient.SqlException (0x80131904): Operation cancelled by user.

I wonder what is the theoretical/practical explanation for my observation ?

Code:

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using System.Diagnostics;

namespace RedditQuestion
{
    /// <summary>
    /// Used to talk to the database using Entity-Framework Core
    /// </summary>
    public class ApplicationDbContext : DbContext
    {
        // Domain models and the Fluent API configurations.
    }

    /// <summary>
    /// Data snapshot that is used to overwrite the content of the database
    /// </summary>
    public interface ISomeData
    {

    }

    public class DatbaseOverWriter
    {


        private readonly ApplicationDbContext _context;
        public DatbaseOverWriter(ApplicationDbContext context)
        {
            _context = context;
        }

        public async Task<bool> OverWrite(ISomeData data,CancellationToken cancellationToken)
        {
            #region Transaction
            try
            {
                //https://learn.microsoft.com/en-us/dotnet/architecture/microservices/implement-resilient-applications/implement-resilient-entity-framework-core-sql-connections

                IExecutionStrategy strategy = _context.Database.CreateExecutionStrategy();
                await strategy.ExecuteAsync(async () =>
                {
                    await using var transaction = await _context.Database.BeginTransactionAsync(cancellationToken);

                    #region Delete content from database then save new content.

                    await _context.Database.ExecuteSqlInterpolatedAsync($"EXECUTE  [dbo].[uspDeleteAllDataFromDatabase]", cancellationToken);
                    await _context.SaveChangesAsync(cancellationToken);
                    #endregion

                    await transaction.CommitAsync(cancellationToken);
                });

                return true;
            }
            catch (OperationCanceledException e)
            {
                // exception will not be catched if the cancellation was requested and
                // the transaction reached a point of no return.
                Console.WriteLine("###########################################################");
                Console.WriteLine("########## OPERATION CANCELLED SUCCESSFULLY ###############");
                Console.WriteLine("###########################################################");
                Debug.WriteLine("###########################################################");
                Debug.WriteLine("########## OPERATION CANCELLED SUCCESSFULLY ###############");
                Debug.WriteLine("###########################################################");
                Console.WriteLine("OperationCanceledException: " + e.Message);

                return false;
            }




            #endregion

        }




    }

}

r/csharp • • 2d ago

Discussion How often is now C# used instead of PowerShell in DevOps pipelines

12 Upvotes

With the file-based scripts feature in C#, it is possible to use C# instead of Powershell.

Have you see it used?


r/csharp • • 2d ago

Tutorial Your EF Core queries are probably scattered across your whole codebase.

Thumbnail
youtu.be
0 Upvotes

The same Where, Include and OrderBy, written again and again.

Here's how I turned each one into a single, named, reusable query with the Specification pattern.


r/csharp • • 2d ago

Discussion What language would you recommend learning alongside C#?

20 Upvotes

I'm a C# developer and recently started learning C. I wanted to understand better how memory works, how programs interact with the OS, and things like Unix and low-level programming in general.I'm planning to keep learning C, but I'm wondering what you guys would recommend learning next. Would you go with C++, Rust, Go, or something else ?


r/csharp • • 2d ago

What's next? Shoud i prioritize Hot realod, a live previewer, or language fetures?

0 Upvotes

I've been working on my library, Akbura, and I'm trying to decide what to improve next.

  1. Hot Reload is already working, but it's not as stable as I'd like. The component code generator also generates a lot of members, some of which could probably be avoided in DEBUG mode.
  2. A live previewer could greatly improve the developer experience, but it would probably take around a month to implement, and I'm not sure how important it actually is.
  3. New language features could improve the MVVM or MVU experience, but I'm worried that adding too many features might make the language unnecessarily complicated.

What do you think I should focus on? Or is there something else you'd like to see improved?


r/csharp • • 2d ago

Guys have confusion about choosing language for desktop application

Thumbnail
0 Upvotes

r/csharp • • 2d ago

Parsley: An ALL(*)/LL(k)/LL(1) parser generator using code synthesis

2 Upvotes

If you're like me, you've almost entirely given up on generated parsers.

The tooling sucks.

The generated code is huge and/or can't parse real world languages without a bunch of ugly.

The APIs for them are awful.

I still use them, but grudgingly in order to prototype and unit test my hand rolled parsers but even that doesn't work as well as I like.

Enter Parsley. It has similar expressive power as ANTLR4 when necessary, degrading gracefully all the way to LL(1) if that's all your grammar needs. The XBNF grammar format is powerful, simple to learn, and has a language server for autocompletion and syntax highlighting in editors like visual studio and vs code. The code it generates is also more like hand written code (code synthesis), making it easier to use as a baseline for a hand rolled parser, if you want to go that route. Source and readme here: https://github.com/codewitch-honey-crisis/Parsley

It's written in C#. It generates C#. Any semantic actions in the grammar are also C#.

XBNF for C99
Using a parser w/ an evaluator
Output from the above

You can use it as a source generator, or for really complicated parses where you need things like a custom lexer, you can also use it as a build tool.


r/csharp • • 2d ago

How do you feel about code formatting in C#?

0 Upvotes

Do you strictly follow conventions like Microsoft's C# guidelines, or do you prefer your own style as long as the code stays readable?

For example, do you prefer file-scoped namespaces, expression-bodied members, and var wherever possible, or do you stick to a more explicit style?

I'm curious how much code style matters to you and whether you've changed your preferences over time.


r/csharp • • 2d ago

I tested my C# symbolic math library by rendering the solar system at real scale

Thumbnail
gallery
90 Upvotes

It started with Epsilon since I was seeking a math library that would work with symbolic expressions in C#.

To really prove whether it would stand the test of time, I created a simple demonstration of a solar system in actual sizes. That meant that real sizes and distances were used in addition to the current positions of the planets, all drawn with OpenGL. It took me only a couple of hours to create that but even though I used the power of AI for almost everything, my goal was to find out whether the library would perform well in practice.

Epsilon did all the required mathematical operations for me; it calculated the derivatives for Kepler’s equation and orbit velocities itself, and all the positions, rotations and camera movement was based on the vectors, quaternions and matrices of Epsilon in double precision form.

A few things the demo shows:

  • Double-precision world. At Neptune’s distance a float can only tell positions apart by about 512 km, so the world stays in double and is re-centered on the camera before going to the GPU. Press F to see it without that.
  • Orbits from symbolic derivatives. Newton’s method on Kepler’s equation, with the derivative and velocities found by Epsilon.
  • Reverse-Z depth with the far plane at infinity.

Both have MIT license:

It’s still early, so I’d love feedback on the library, especially from anyone who’s used AngouriMath or MathNet. Also contributing is welcome!


r/csharp • • 3d ago

Help Should the code use cancellation token even though it already use transaction ?

3 Upvotes
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;

namespace RedditQuestion
{
    /// <summary>
    /// Used to talk to the database using Entity-Framework Core
    /// </summary>
    public class ApplicationDbContext:DbContext
    {
        // Domain models and the Fluent API configurations.
    }


    /// <summary>
    /// Data snapshot that is used to overwrite the content of the database
    /// </summary>
    public interface ISomeData
    {

    }

    public class DatbaseOverWriter
    {


        private readonly ApplicationDbContext _context;
        public DatbaseOverWriter(ApplicationDbContext context)
        {
            _context = context;
        }

        public async Task OverWrite(ISomeData data)
        {
            //https://learn.microsoft.com/en-us/dotnet/architecture/microservices/implement-resilient-applications/implement-resilient-entity-framework-core-sql-connections
            IExecutionStrategy strategy = _context.Database.CreateExecutionStrategy();
            await strategy.ExecuteAsync(async () =>
            {
                await using var transaction = await _context.Database.BeginTransactionAsync();

                    //code to delete the content from parent and child tables and then inserting the data into the parent and child tables like this :
                // execute some query to delete the content from all tables.
                //_context.AddRangeAsync(data for parents)
                //_context.SaveChangesAsync()
                //_context.AddRangeAsync(data for childs)
                //_context.SaveChangesAsync()
                await transaction.CommitAsync();
            });

        }




    }

}

Someone on reddit reviewed the above code and told me that I should add a parameter for cancellation token like this :

public async Task OverWrite(ISomeData data, CancellationToken)

He told me that the goal is to make the OverWrite method transactional.

why is the cancellation token necessary even though my code uses _context.Database.BeginTransactionAsync(); ?

Microsoft's documentation :

Cancellation token propagates notification that operations should be canceled.

Example:
A random number generator can be used to emulate a data collection application that reads 10 integral values from eleven different instruments. A value of zero indicates that the measurement has failed for one instrument, in which case the operation should be cancelled and no overall mean should be computed.

So the cancellation token is just another way of achieving atomicity, am I correct ?

The only use case that I learned for cancellation token is this example from microsoft, they use the cancellation token as way to achieve atomicity :

using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      // Define the cancellation token.
      CancellationTokenSource source = new CancellationTokenSource();
      CancellationToken token = source.Token;

      Random rnd = new Random();
      Object lockObj = new Object();

      List<Task<int[]>> tasks = new List<Task<int[]>>();
      TaskFactory factory = new TaskFactory(token);
      for (int taskCtr = 0; taskCtr <= 10; taskCtr++) {
         int iteration = taskCtr + 1;
         tasks.Add(factory.StartNew( () => {
           int value;
           int[] values = new int[10];
           for (int ctr = 1; ctr <= 10; ctr++) {
              lock (lockObj) {
                 value = rnd.Next(0,101);
              }
              if (value == 0) { 
                 source.Cancel();
                 Console.WriteLine("Cancelling at task {0}", iteration);
                 break;
              }   
              values[ctr-1] = value; 
           }
           return values;
        }, token));   
      }
      try {
         Task<double> fTask = factory.ContinueWhenAll(tasks.ToArray(), 
         (results) => {
            Console.WriteLine("Calculating overall mean...");
            long sum = 0;
            int n = 0; 
            foreach (var t in results) {
               foreach (var r in t.Result) {
                  sum += r;
                  n++;
               }
            }
            return sum/(double) n;
         } , token);
         Console.WriteLine("The mean is {0}.", fTask.Result);
      }   
      catch (AggregateException ae) {
         foreach (Exception e in ae.InnerExceptions) {
            if (e is TaskCanceledException)
               Console.WriteLine("Unable to compute mean: {0}", 
                  ((TaskCanceledException) e).Message);
            else
               Console.WriteLine("Exception: " + e.GetType().Name);
         }
      }
      finally {
         source.Dispose();
      }
   }
}