/r/csharp

Photograph via snooOG

All about the object-oriented programming language C#.

Information about Reddit's API changes, the unprofessional conduct of the CEO, and their response to the community's concerns regarding 3rd party apps, moderator tools, anti-spam/anti-bot tools, and accessibility options that will be impacted can be found in the associated Wikipedia article: https://en.wikipedia.org/wiki/2023_Reddit_API_controversy

Alternative C# communities available outside Reddit on Lemmy and Discord:


All about the object-oriented programming language C#.


Getting Started
C# Fundamentals: Development for Absolute Beginners

Useful MSDN Resources
A Tour of the C# Language
Get started with .NET in 5 minutes
C# Guide
C# Language Reference
C# Programing Guide
C# Coding Conventions
.NET Framework Reference Source Code

Other Resources
C# Yellow Book
Dot Net Perls
The C# Player's Guide

IDEs
Visual Studio
MonoDevelop (Windows/Mac/Linux)
Rider (Windows/Mac/Linux)

Tools
ILSpy
dotPeek
LINQPad

Alternative Communities
C# Discord Group
C# Lemmy Community
dotnet Lemmy Community

Related Subreddits
/r/dotnet
/r/azure
/r/learncsharp
/r/learnprogramming
/r/programming
/r/dailyprogrammer
/r/programmingbuddies
/r/cshighschoolers

Additional .NET Languages
/r/fsharp
/r/visualbasic

Platform-specific Subreddits
/r/windowsdev
/r/AZURE
/r/Xamarin
/r/Unity3D
/r/WPDev

Rules:

  • Rule 1: No job postings (For Hire and Hiring)
  • Rule 2: No malicious, intentionally harmful, or piracy-related software
  • Rule 3: Posts should be directly relevant to C#
  • Rule 4: Request-for-help posts should be made with effort
  • Rule 5: No hostility towards users for any reason
  • Rule 6: No spam of tools/companies/advertisements
  • Rule 7: Submitted links to be made with effort and quality
  • Rule 8: No unattributed use or automated use of AI Generation Tools

Read detailed descriptions of the rules here.

/r/csharp

276,219 Subscribers

0

Implementing a list of lists

Hey all, I have a bit of messy code and was wondering if there was a better way to do things.

Lets say I have a Person who has a set of ShoppingLists for different shops:

public class Person 
{
public string Name { get; set; } 
public List<ShoppingLists> { get; set; } 
}
public record ShoppingLists { public List<Item> IItems }

public class Item
{
public string Name { get; }
public string Color { get; }
}
public class Carrot: Item { }
public class Cucumber { }

To implement this I end up with the following:

Person steve= new Person("Steve", new List<ShoppingLists> { new List<Item> { new Carrot() }, new List<Item> { new Cucumber() } });

I think that is just about right, be there in lies my issue. That is a very confusing statement with all the new declarations. How would you go about setting this up? Is there a trick I am missing?

Best solution I have found is to use temporary variables to set up each step and then pass them up like this:

ShoppingLists shopOne = new (new List<Item>);
shopOne.Add(new Carrot());

ShoppingLists shopTwo = new (new List<Item>);
shopOne.Add(new Cucumber());

Person steve = new Person("Steve", new List<ShoppingLists> { shopOne, shopTwo }

But not sure if this is the best approach either?

Thanks for any advice.

1 Comment
2024/11/22
05:35 UTC

1

[WPF] Help with Combobox using microsoft.xaml.behaviors.wpf event binding

Hi, sorry to post a "how do I do this?" but I've been banging my head against this wall for a while now.

I'm using microsoft.xaml.behaviors.wpf in order to be able to bind events to commands from the xaml.

<DataGridTemplateColumn Header="MyHeader">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding DataProperty}" />
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
    <DataGridTemplateColumn.CellEditingTemplate>
        <DataTemplate>
            <ComboBox IsEditable="True"
                      StaysOpenOnEdit="True">
                <i:Interaction.Triggers>
                    <i:EventTrigger EventName="TextChanged">
                        <i:InvokeCommandAction Command="{Binding MyCommand, RelativeSource={RelativeSource AncestorType=Window}}"
                                               CommandParameter="{Binding Text, RelativeSource={RelativeSource Self}}" />
                    </i:EventTrigger>
                </i:Interaction.Triggers>
            </ComboBox>
        </DataTemplate>
    </DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>

This TextChanged event does not fire. As far as I understand, that is because the Combobox doesn't actually have such an event. Rather, there is a TextChanged event associated with the Textbox that the Combobox uses (for entering text), however the ComboBox does not expose that Textbox event. I assume I will find a similar issue with the CommandParameter I am trying to pass (but I'm not certain about that). So, how can I bind a Command to the event of having the text in the combobox change?

Any help is much appreciated.

// Edit: I should also say, there is a chance I am wrong in my diagnosis. For a while I assumed the issue was with the source of the binding (because "MyCommand" is a property of a VM which is the DataContext for the window, but the DataGrid is bound to a collection of a different VM (which is a property on the original VM). I think the RelativeSource addresses this, but again I'm not sure.

The code in the App.xaml.cs which instantiates the various objects and sets the actual command delegates executes fine, but nothing happens when you enter text. It's been hard to debug since I don't know exactly what's going wrong, but this is the best information I have about it as of now.

0 Comments
2024/11/22
04:55 UTC

1

I am having an issue with GMAIL SMTP in a C# program

I want to use C# do to a necessary mass emailing of hundreds of receiving email addresses. I have a gmail account and I believe my message will be better received if it comes from my personal gmail account instead of from one of my website's email accounts. But if I do not resolve this issue, I might resort to trying something else.

A youtube tutorial for setting up a C# program for sending GMail messages has instructed me to first set up two tier authentication. So I did that. Then this tutorial suggested that I use a special feature in the Google Account Settings of creating an App ID with a unique 16 character special password. If you like, I can add more specifics and content about this and post a link to the youtube tutorial.

It did not work and the line of code where, after I set up the parameters of a message, I use the SMTP command to send the message an error is thrown.

It almost seems that there is so much security protocols surrounding GMail now that Google has made it virtually impossible for someone to write a C# program to make tasks easier.

On the other hand, I have an active Email server, Thunderbird, that I use. So there must be a correct way to use Gmail in a desktop App and I assume a software developer can write a program to do what I am wanting to accomplish.

3 Comments
2024/11/22
04:28 UTC

2

My Winforms program has user data, but it detects the wrong values when I put the contents of bin/release in another folder

I don't really know how to explain this properly, but basically I use reelase in Visual Studio 2022:

Release

I have this settings file:

I have a boolean value

The prgram checks the content of variable in one file and changes the value to True in another file

https://preview.redd.it/n0k80ot39c2e1.png?width=418&format=png&auto=webp&s=567de2acdd9d8ebdfb9b3221a7f3e3d8d3321aa5

https://preview.redd.it/aa9at5379c2e1.png?width=373&format=png&auto=webp&s=757306b464efac625a965950726df629264e51c9

The issue is that when i go to (project folder)/Bin/Release and copy the .exe file and the other necessary files, the program acts like if the value is True. These are the files that I copy and paste into a folder in my downloads folder:

https://preview.redd.it/jjjenv1o9c2e1.png?width=623&format=png&auto=webp&s=23a63ae0a8833ae96a55fd97c68ed9b2a33c3a00

I also put a folder called "Source" and after that, even if I remove the folder and only leave this 4 items, it still acts like if the value is true.

I'm very new to C# so I don't know what did I do wrong. I also don't know if the version I installed is outdated, and the program works perfectly fine when I run it in Visual Studio

Edit: if you want to download the files or check the code go here: https://drive.google.com/drive/folders/1oUuRpHTXQNiwSiGzK_TzM2XZtN3xDNf-?usp=sharing

Also I think my Visual Studio installation could be broken so if you have any tips to check if my installation is broken tell me

1 Comment
2024/11/21
23:29 UTC

0

The instance of SQL Server you attempted to connect to does not support encryption.

I have been having tough time resolving this problem, I need help please

9 Comments
2024/11/21
21:23 UTC

2

what could be causing this off-by-one error?

I'm doing Advent of Code 2015 day 5 and cant for the life of me figure out why my code doesn't compute the correct answer for part 1 (i found out the correct answer is 238 but my program computes 239). It is especially hard because it does compute all the correct answers to the given example strings in the problem description. I've also tried looking at a few random samples of the strings it marks as "nice" and "not nice" and manually validating them and i haven't found a mistake yet.

Here is my code, the primary algorithm for the puzzle solution is within the bool isNiceString(string str) method. There is also a bool isNiceString_slow(string str) method which is a simpler version that i added just to assert it wouldn't have any discrepancy with my first, more complex, version (figured i might have messed up the logic). Both versions give the same answer.

I'm linking my whole repo instead of just todays code because at this point im honestly not sure if the issue is caused by the algorithm or my implementation or by something external to todays specific code. I have been looking through the way im reading the input and validating its actually correct but i just cant find any issues.

EDIT: silly mistake, i was looking for "qp" instead of "pq" (apparently i had made the mistake in both versions). Thanks for the help.

3 Comments
2024/11/21
19:46 UTC

0

Can't run any .NET application on Linux systems after 9.0 dropped

I can't run any .NET application on my internal NVME drives since upgrading to 9.0

When I try and run via rider or any other IDE

Error running 'Sadie. Console' Cannot run program "/ media/ ash/ STORAGE/ dev/ h/ SadieEmulator/ Sadie. Console/ bin/ Debug/ net9.0/ Sadie. Console" (in directory "/ media/ ash/ STORAGE/ dev/ h/ SadieEmulator/ Sadie. Console/ bin/ Debug/ net9.0"): error=13, Permission denied

Manually via CLI running dotnet run --project...

Unhandled exception: System.ComponentModel.Win32Exception (13): An error occurred trying to start process '/media/ash/STORAGE/dev/h/SadieEmulator/Sadie.Console/bin/Debug/net9.0/Sadie.Console' with working directory '/media/ash/STORAGE/dev/h/SadieEmulator'. Permission deniedUnhandled exception: System.ComponentModel.Win32Exception (13): An error occurred trying to start process '/media/ash/STORAGE/dev/h/SadieEmulator/Sadie.Console/bin/Debug/net9.0/Sadie.Console' with working directory '/media/ash/STORAGE/dev/h/SadieEmulator'. Permission denied

even a sudo chmod -R 777 doesn't fix this... so how do we fix this since the .NET 9 drop clearly is flawed?

9 Comments
2024/11/21
19:36 UTC

17

Phosphorus.NET - Windows Application hosting a Web App

I really like blazor, but I was wondering if I can have something similar to Electron, but using C# on the native side.

The idea excited my mind and after researching/trying the WebView2 component, I really didn't like the developer experience it gave when it comes to interoperability with C#.

Hence this is how I made PhosphorusNET, a library to help bridge that gap with a better DX.

It's still v0.0.1, just testing the waters with small projects and see what comes out of it. At a first glance I really like it but it's a bit rough around the edges, needs more work. I really like how lightweight the result is, after publishing a single-executable framework-dependent application it comes around to 3-4mbs of storage and ~50-100mb of RAM (using React).

I'd be glad to hear your feedback on the library!

https://github.com/UltraWelfare/Phosphorus.NET

13 Comments
2024/11/21
19:14 UTC

3

Trying to add an image to my Resources.resx, but it keeps creating a new folder outside of it's directory

very very new to using C#, and im trying to add an image into the Resources.resx file so i can use it as a default icon for MP3 files i drag into the app, but when i try to follow along and add it under Resources.resx, it creates a new folder called "Resources" outside of my Properties folder, and thats not where it needs to be. anyone know what to do or if im just doing something wrong?

https://preview.redd.it/5lno90i1ja2e1.png?width=928&format=png&auto=webp&s=8e3877e13044c3f1dfb7a45c120f15a858fa9b19

https://preview.redd.it/re6r27s2ja2e1.png?width=457&format=png&auto=webp&s=2a1450c056dfb9fbcc87e1596b0b13a8d5a430fb

https://preview.redd.it/w6i3z594ja2e1.png?width=515&format=png&auto=webp&s=5c0d8bb30e3d8926322c6f6386dc801478d01f30

https://preview.redd.it/rxptj7m5ja2e1.png?width=532&format=png&auto=webp&s=409dbedc830f3123b298cfb9f99b09e90b23ab62

3 Comments
2024/11/21
17:35 UTC

0

If I learn and program C# will that program be able to run on Linux via dotnet?

If I learn and program C# will that program be able to run on Linux via dotnet? Or do you have to change the way you program for that feature?

20 Comments
2024/11/21
16:36 UTC

1

Domain Driven Design and Clean Architecture – Project template with MassTransit, CQRS, and RabbitMQ

1 Comment
2024/11/21
14:11 UTC

1

BenchmarkDotNet project in Docker container

Hi guys!
I'm pretty new both in c-sharp and benchmarkdotnet but does anyone have any experience with running benchmarks in a docker container? I am having a lot of trouble and at first I thought the problem was with my DockerFile but no I just now realized that I need to change the Toolchain configuration in my Program.cs if I want to make this happen.
This is what happens with my regular DockerFile, with all .dll's in place. Basically the benchmarking does "happen", I get to the end with the results table but the result is NA because no benchmarks were run.

console log before [InProcess] attribute

*/app/tests/benchmark is the docker path specified where the benchmark project is present

Then I added this annotation [InProcess] in my BenchmarkBase class and things start to improve a bit because in my console log I can see benchmarks running but the results table is still without any results.

Part 1 of console log - looks like things are running correctly

Part 2 of console log - first error noticed

Part 3 of console log - looks like no results were retrieved

Results table is without results

Could I please have some guidance on how to fix this? Do I need to do a custom toolchain? I am feeling a bit clueless right now, so I'd appreciate any help!

0 Comments
2024/11/21
13:46 UTC

3

Security Headers should be added on Backend or Frontend side?

Hi. I have seperated C# API backend from React front. On which side should Security Headers be added? Im asking because, in some blogs i see that for example "Content Security Policy" is applied in C# API backend, but i cant see any purpose here, cuz with CSP (how i understand) we limiting or setting rules that tell the browser what it is allowed to load(css styles, js scripts, images and etc.) from where, from which resource. For example lets take this CSP header - "Content-Security-Policy: img-src 'self' https://api.testApp.com;" - now in our app images can be loaded ONLY from:

  1. The same origin as my website(if my site is https://mytestapp.com, images must also come from https://mytestapp.com).
  2. From api : "https://api.testApp.com"

(CSP is just example here, my question is applicable for other headers too) Now my question is, what is purpose of implementing this(CSP and other headers...) header in restful c# api backend?

Can someone write a plain english overview which type of headers should be set on front side, which headers should be set on back side?. And this answer is generated by gpt, can we agree with him? or any improvements?

Where Should the Headers Be Applied?

> Backend (API):

--- Use security headers on the API to protect data and restrict how the API is accessed.

--- Critical headers: CORS, HSTS, X-Content-Type-Options, Content-Security-Policy (minimalist).

> Frontend (React App):

--- Use headers to protect the delivery of your React app to the browser.

--- Critical headers: CSP, X-Frame-Options, X-Content-Type-Options, Referrer-Policy, Permissions-Policy.

3 Comments
2024/11/21
12:34 UTC

1

Need Guidance for Starting My Graduation Project (Health/AI Focus)

Hi everyone!

I’m in my final year at the Faculty of Computers and Information, working on my graduation project. The idea is to develop a mobile application that uses AI to analyze uploaded photos and determine if the person might have Alzheimer’s disease. This project aims to provide a health-tech solution for early detection.

Here’s some context:

Team Structure: We’re a team of five (AI specialist, Flutter developer, UI/UX designer, .NET back-end developer [me], and another member).

My Role: I’m responsible for building the API using .NET 8.0.

Current Status:

I’ve almost completed studying APIs.

I’ve already studied key concepts like MVC, LINQ, and Entity Framework (EF Core).

I’m now preparing to apply my knowledge and start implementing the API.

I’m looking for advice on:

  1. The best way to start building such an API.

  2. Any resources or open-source projects (preferably in .NET) I can learn from or adapt to save time.

  3. How to effectively split tasks within the team to stay on track and meet deadlines.

The project involves image processing, so I’d appreciate recommendations for libraries or tools to facilitate this.

Thanks a lot for any guidance or suggestions you can share!

0 Comments
2024/11/21
10:32 UTC

26

HttpGET or HttpPost if you want to send a complex filter query in order to get some data back from the API?

HttpGET or HttpPost if you want to send a complex filter query in order to get some data back from the API?

Lets say you have a list that can contain quite many objects (like 1000) that you want to filter to get the data e.g.:

{
  animal1, animal2, animal3....animal1000
}
64 Comments
2024/11/21
09:55 UTC

33

Modular coding is really confusing to me.

I think I am a pretty good and conscientious programmer, but I am always striving for more modularity and less dependency. But as I have been looking more into modularity, and trying to make my code as flexible as possible, I get confused on how to actually achieve this. It seems the goal of modularity in code is to be able to remove certain elements from different classes, and not have it affect other objects not related to that code, because it does not depend on the internal structure of the code you have modified. But, how does this actually work in practice? In my mind, no matter what object you create, if it interacts at all with another script, won’t there always be some level of dependency there? And what if you deleted that object from your namespace altogether?.. I am trying to understand exactly what modularity is and how to accomplish it. Curious to hear the ways my understanding might be short sighted.

35 Comments
2024/11/21
07:41 UTC

0

Visual Studio workloads for learning to build C# desktop Applications.

I'm teaching myself C# and hope to build some basic apps like a postage calculator etc. What should I select under the workload tab when installing Visual Studio to be able to build such apps. There won't be any databases involved. Just basic logic. Much like a calculator. Will selecting the ".NET desktop development" option be sufficient?

8 Comments
2024/11/21
07:05 UTC

0

Rate my OOP code

Hello,

Thanks to the users of this subreddit, I learned more about good practices in OOP.

Would you like to rate this code from 1 to 10, please?:

namespace practice_mk_2
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Characters
            string[] goodForces = [
                "Liu Kang",
                "Scorpion",
                "Sub Zero",
                "Raiden"
            ];

            string[] evilForces = [
                "Shao Kahn",
                "Shang Tsung",
                "Goro",
                "Kintaro"
            ];

            // HealthLogic instance
            HealthLogic healthLogic = new HealthLogic();

            // Define good forces
            Character good1 = new Character(goodForces[0], healthLogic.BossHealth(goodForces[0]));
            Character good2 = new Character(goodForces[1], healthLogic.BossHealth(goodForces[1]));
            Character good3 = new Character(goodForces[2], healthLogic.BossHealth(goodForces[2]));
            Character good4 = new Character(goodForces[3], healthLogic.BossHealth(goodForces[3]));

            // Define evil forces
            Character evil1 = new Character(evilForces[0], healthLogic.BossHealth(evilForces[0]));
            Character evil2 = new Character(evilForces[1], healthLogic.BossHealth(evilForces[1]));
            Character evil3 = new Character(evilForces[2], healthLogic.BossHealth(evilForces[2]));
            Character evil4 = new Character(evilForces[3], healthLogic.BossHealth(evilForces[3]));
        }
    }
    internal class Character
    {
        public string Name { get; private set; }
        public int Health { get; private set; }

        public Character(string name, int health)
        {
            Name = name;
            Health = health;
            Console.WriteLine($"{Name}, {Health}");
        }
    }
    internal class HealthLogic
    {
        public int BossHealth(string name)
        {
            if (name == "Shao Kahn" || name == "Goro" || name == "Kintaro")
            {
                return 200;
            }
            else
            {
                return 100;
            }
        }
    }
}

Thanks.

10 Comments
2024/11/21
05:49 UTC

2

Programming Support

I am an upcoming software engineer who is eager for self improvement in computer programming,Apparently I’ve completed a software engineering diploma course but I’m still not satisfied with what I’ve learnt from there so far and based on the kind of environment I’m in, I’m not able to get the support I need to get more understanding into the language concept(c#, swift and c++) I’m trying to specialise in. Please help me, I want to become pro in this programming thing. I’m not able to even sleep, I’m always up and behind my laptop trying to do something, it’s really frustrating and I don’t want to give up. I’m doing this for myself and my mom, I owe her a lot. If anyone could please help me out in anyway I’ll be very grateful.

6 Comments
2024/11/21
00:23 UTC

2

I don't understand SystemColors in WPF

https://learn.microsoft.com/en-us/dotnet/api/system.windows.systemcolors?view=windowsdesktop-8.0

I'm now using System.Windows.SystemColors but I can't get my original gradient colors to work. I always end up with gradients that resemble the Windows Aero theme so to speak. Is there no way to use System.Windows.SystemColors and still use my originally defined gradients?

7 Comments
2024/11/20
21:53 UTC

0

I need a Github repository with a fully unit tested API, using a mocking framework other than Moq

Ideally using Xunit but not obligatory. Other tests such as integration and system tests would be great too but currently I am focused on unit testing. I am also struggling to figure out what to write unit tests for, because testing endpoints in controllers will be handled by integration tests for example and therefore seem pointless, it only makes sense to unit test specific buisness logic code in isolation but this will result in low code coverage. lf but I find most repositories use Moq which should never be used anymore due to recent controversy.

15 Comments
2024/11/20
16:51 UTC

9

what is the best tool for C# to handle SQL schema migrations? I am looking for something like flyway or luquibase but don't want Java in my infrastructure.

33 Comments
2024/11/20
16:16 UTC

0

Streamlining .NET Development with Practical Aspects

Aspect-oriented programming (AOP) provides a robust approach to encapsulate cross-cutting concerns into reusable components called aspects. By separating these concerns from business logic, AOP helps streamline development, reduce boilerplate code, and enhance maintainability. In this article, I’ll explore three practical aspects that I am using for almost all my projects: Notify, Log, and Bindable, demonstrating how they simplify common programming tasks and improve code quality.

All examples (one, two, three) are implemented using the Aspect Injector, but the same logic can be adapted to other AOP frameworks. This approach is not tied to any specific library and can be easily customized to fit your project’s needs.

1 Comment
2024/11/20
15:03 UTC

48

Playing around with cellular automata based map generation in WinForms to avoid "Reloading Domain" every 10 seconds in Unity. Thought some WinForms content might be appreciated here.

5 Comments
2024/11/20
13:09 UTC

0

Struggle getting data from HTTP request in .NET MAUI application

11 Comments
2024/11/20
12:02 UTC

0

Call a C# function on a query refresh in Excel with VSTO

Hi,

I am trying to create an excel Add-in, where i need to call a function from the add-in when a query/connection is refreshed. I am unable to find much guidance on it, and i am unable to find something that works. The function needs to be called whenever a refresh is called. It does not matter what query is refreshed. If necessary, the mCode for the queries can also be altered.

Thanks for any help in advance, im a bit lost:)

3 Comments
2024/11/20
09:15 UTC

2

Closing/Reopening TCP Listener Server

I have a TCP listen server that I need to start with a "Open Comms" button and then stop with a "Close Comms" button. It all works until I click "Close Comms" and then try to restart the server by clicking "Open Comms" again. At that point, I see that the accept callback is hit, but it no longer triggers the ReadCallback from _socket.BeginReceive (async callback mode).

Any ideas why this works the first time and not the others?

For "closing" the listen server, I'm calling _socket.Shutdown(SocketShutdown.Both); and then _socket.Close();

Completely closing down the app and restarting always gets it unstuck.

4 Comments
2024/11/19
23:21 UTC

0

ASP.NET and Django. What's the difference?

I'd like to say that I'm not looking for an answer about which one is better, but that's a lie. However, this is subjective for everyone.

If there are anyone here who has experience with both ASP.NET and Django, please share your impressions.

P.S. I searched, but if anyone made a comparison, it was years ago!

9 Comments
2024/11/19
21:48 UTC

Back To Top