/r/csharp

Photograph via snooOG

All about the object-oriented programming language C#.

Information about Reddit's proposed 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 10 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

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

254,154 Subscribers

0

Can anyone give me tips or advice, how I could add encryption to my storage page for passwords?

10 Comments
2024/05/06
07:54 UTC

0

Crossposting from k8s, since I'm unable to figure out what to do. I have added it as JsonFile, with the mounted path. I'm holding on using the ConfigMapFileProvider package because I want to try it without new packages. PLease let me know what I can do

2 Comments
2024/05/06
06:54 UTC

0

Machine learning with C#? any courses please?

As the title suggests I'm trying to learn machine learning using C# if anyone has any good courses to buy or for free would be appreciated!

9 Comments
2024/05/05
23:39 UTC

8

Early career advice? No mentor

I'm in my mid 30s, I've been in leadership and senior positions in my past industry. I've been a computer nerd my entire life, and a year and a half ago I went to a community college to begin the degree process for CS. So that will take a while, but I have a network admin / software developer / IT guy role for this company I've been with for ~ 6mo. They're happy, and I'm happy.

I don't have a mentor that can teach or guide me through anything. Which is fine mostly, I love problem solving. The biggest issue is that I am missing out on larger concepts like interfaces, dependency injection, and who knows what else. I come from C++, my schooling is C++. But, I feel like C# is where the market is shifting to in the areas I'm interested in. And its what I've made all my work projects in because every API that I interact with uses C#.

What suggestions for books, courses, frameworks to learn, or things to avoid over the next 5 years?

9 Comments
2024/05/05
17:26 UTC

0

What does this mean?

it says the potential fix is to remove the health -= 1 line, but how can i decrease the health if i remove that statement?

64 Comments
2024/05/05
16:26 UTC

6

I just updated Visual Studio 2019 Community Edition on Windows and it said some of my selections are no longer supported. How do I change them?

The selections no longer supported are:

.NET Core 3.1 Runtime

.NET SDK

.NET cross-platform development

11 Comments
2024/05/05
15:11 UTC

8

Visual FA 1.4 is released

https://preview.redd.it/r7e3w9ggemyc1.jpg?width=128&format=pjpg&auto=webp&s=30b8b46b4a9671a8a1dd520a41742ad80eb90cd3

Visual FA is a fast lexing/tokenization engine that can operate at runtime, compile assemblies of lexers directly, or generate code (even dependency free code) to include in your projects. This is useful for parsing and scraping, but it can also be used for generalized matching and even field validation.

It may seem similar to Microsoft .NET's Regular Expression engine but it doesn't backtrack, so it operates about 3 times as fast, and more importantly it can be used for lexing/tokenizing text.

Nuget packages

Visual FA runtime library: https://www.nuget.org/packages/VisualFA

Visual FA Source Generator (C#9 or better) https://www.nuget.org/packages/VisualFA.SourceGenerator

Visual FA Generator (Generates in VB.NET or C#6 or better) https://www.nuget.org/packages/VisualFA.Generator

Visual FA Compiler (used if you want functionality similar to RegexOptions.Compiled https://www.nuget.org/packages/VisualFA.Compiler

Source code and examples

https://github.com/codewitch-honey-crisis/VisualFA

Articles

0 Comments
2024/05/05
14:44 UTC

3

VSTO reference material and alternatives?

Are there any good reference materials for VSTO? Either as a book or online documentation or a course of some sort. It seems to me that information is a bit scarce when I try and figure out what does what, and I have been quite reliant on ChatGPT for the most part, which I am not a fan of relying on so heavily at this stage.

I understand that it is probably going to stay on the .NET Framework and probably in the long term... not the best option, but what are the alternatives? At work we still primarily use the desktop version of Microsoft office (2019) and some of our PCs have no connectivity to the internet. I also hate the web app versions of Office so there's that.

Would love to know if VSTO is really the best direction before I get too deep into it.

Background:

I'm an engineer, not a software programmer. But I do have some basic background with programming in various languages (matlab, python, C#, rudimentary VBA) and know enough to understand the basics (if-else, try-catch, basic data structure like hash tables and trees).

I primarily use VSTO to automate work in excel, and to link excel to other design software API. The main design software can interface with other languages like VBA and python as well, but VBA and C# has the best documentation and is the easiest to work with. In the future, it is likely that I will need to work in languages other than C# for other APIs.

I am loving the capabilities of VSTO so far, as I can make work panes and make use of excel as the base user interface to pull and manipulate data with VSTO, while allowing for users to easily edit the input & output in an environment which they are already very familiar and capable in.

1 Comment
2024/05/05
13:24 UTC

99

I rarely use interfaces

In currently learning to code in .NET and ive been doing it for a few months now.

However, I almost never use interfaces. I think i have a good understanding of what they do, but i never felt the need to use them.

Maybe its because Im only working on my own small projects/ School projects. And i will see the need for them later on big projects?

I mean, if i have a method that adds an user to the db. Why should i use an IUser as parameter instead of just an User? Except for ”loose coupling”.

147 Comments
2024/05/05
09:18 UTC

24

In total absolute dum-dum terms, what is the simple functional difference between accessors, auto-properties, expression bodies member and so on...

There are so many options now for how you can write what is 'essentially' an accessor.

I never know when to use one or the other, but I have found that most of the time, when I use an auto-property I end up changing it soon after as they don't allow you so assign to them like they're a private variable (even with a private set...?)

I have also found in my time essentially teaching myself programming over the last 15 years, that usually when something has a specific and slightly restrictive use like this, it's because you're trying to use it wrong. finding out the answers to these questions usually improves my code hugely.

So, please, any enlightenment you can give me would be wonderful. Thank you!

17 Comments
2024/05/05
08:53 UTC

0

Why Constant initialiser must be compile time constant and what are the different types of compile time as well as run time constants ?

18 Comments
2024/05/04
19:03 UTC

0

Need some help in a project

https://pastebin.com/yfQQuyhB

After I enter A cell value

This is the supposed output
What cell would you like to analyze? a1

Cell Coordinates (0,0)

Box Coordinates (0,0)

Row Values: 4, 9

Column Values: 9, 1

Box Values: 8, 9, 2

Row Hints: 1, 2, 3, 5, 6, 7, 8

Column Hints: 2, 3, 4, 5, 6, 7, 8

Box Hints: 1, 3, 4, 5, 6, 7

Possible Answers: 3, 5, 6, 7

What do you like to perform?

1 - Provide an answer for this cell

2 - Check another cell

3 - Reset the Puzzle

4 - Exit the application

But only the what would you like to perform part shows.

1 Comment
2024/05/04
18:58 UTC

18

Memory leaks in WPF

What are the usual cause for memory leaks in wpf that used prism for MVVM? My viewmodel model usually contains observable collections, full property that used prism bindable, observable collections, and event aggregator subscribe's and publish. I have a baseviewmodel that implements the IDisposable and the dispose method is virtual so the child viewmodel will implement the Dispose method that will unsubscribe all the event aggregators. When I put breakpoint on the Dispose method, it doesn't get hit. Why did I do wrong here, also what may cause the issue on memory leaks? Thanks.

14 Comments
2024/05/04
15:13 UTC

7

[WPF] DataContext confusion using custom user control in a list view

I'm having trouble getting a button Command binding to work when using a custom user control as the item template of a ListView control. Using Snoop, it looks like my binding is broken but I can't work out where it's breaking.

My custom user control:

SavedBook.xaml

<UserControl ...
    >
    <Grid>
        <Button
            x:Name="MoreButton"
            Content="{Binding BookName, RelativeSource={RelativeSource FindAncestor, AncestorType=UserControl}}"
            Command="{Binding MoreButtonClickedCommand, RelativeSource={RelativeSource FindAncestor, AncestorType=Window}}">
    </Grid>
</UserControl>

And the code behind:

SavedBook.xaml.cs

public partial class SavedBook : UserControl
{
    public static readonly DependencyProperty BookNameProperty =
        DependencyProperty.Register(
            nameof(BookName),
            typeof(string),
            typeof(SavedBook),
            new PropertyMetadata(string.Empty));

    public static readonly DependencyProperty MoreButtonClickedCommandProperty =
        DependencyProperty.Register(
            nameof(MoreButtonClickedCommand),
            typeof(ICommand),
            typeof(SavedBook),
            new PropertyMetadata(null));

    public string BookName
    {
        get => (string)GetValue(BookNameProperty);
        set => SetValue(BookNameProperty, value);
    }

    public ICommand MoreButtonClickedCommand
    {
        get => (ICommand)GetValue(MoreButtonClickedCommandProperty);
        set => SetValue(MoreButtonClickedCommandProperty, value);
    }

    public SavedBook()
    {
        InitializeComponent();
    }
}

I use this user control as an item in a list view in a Window:

ManageBooks.xaml

<Window ...
    >
    <Grid>
        <ListView
            x:Name="SavedBooksListView"
            ItemsSource="{Binding SavedBooks}">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <local:SavedBook
                        BookName="{Binding Name}"
                        MoreButtonClickedCommand="{Binding DataContext.SavedBookMoreButtonClickedCommand, ElementName=SavedBooksListView}"/>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </Grid>
</Window>

And in it's code behind:

ManageBooks.xaml.cs

public partial class ManageBooks : Window, INotifyPropertyChanged
{
    private List<Book>? savedBooks;

    public List<Book>? SavedBooks
    {
        get => savedBooks;
        set
        {
            savedBooks = value;
            OnPropertyChanged(nameof(SavedBooks));
        }
    }

    public ICommand SavedBookMoreButtonClickedCommand { get; }

    public event PropertyChangedEventHandler? PropertyChanged;

    public ManageBooks(List<Book> savedBooks)
    {
        SavedBooks = savedBooks;
        DataContext = this;

        SavedBookMoreButtonClickedCommand = new RelayCommand(new Action<object?>(OnSavedBookMoreButtonClicked));
    }

    public void OnPropertyChanged(string parameterName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(parameterName));
    }

    private void OnSavedBookMoreButtonClicked(object? obj)
    {
        throw new NotImplementedException();
    }
}

Where I'm using a standard format for the RelayCommand. And my Book class is as follows:

Book.cs

public class Book
{
    public string Name = string.Empty;
}

Now this window is called as a dialog from a view-model:

NavigationBarViewModel.cs

public class NavigationBarViewModel
{
    List<Book> SavedBooks = new()
    {
        new Book() { Name = "Test 1" },
        new Book() { Name = "Test 2" },
    };

    public NavigationBarViewModel() { }

    public void OpenManageBooksDialog()
    {
        ManageBooks dlg = new ManageBooks(SavedBooks);
        dlg.Show();
    }

Now when the OpenManageBooksDialog() method is called, the ManageBooks dialog is opened and the list view is populated with 2 SavedBook user controls. However, clicking the MoreButton does nothing (i.e. throwing the NotImplementedException that it should)).

Using Snoop, I'm given the following error at the Command for the MoreButton:

System.Windows.Data Error: 40 : BindingExpression path error: 'MoreButtonClickedCommand' property not found on 'object' ''ManageBooks' (Name='')'. BindingExpression:Path=MoreButtonClickedCommand; DataItem='ManageBooks' (Name=''); target element is 'Button' (Name='MoreButton'); target property is 'Command' (type 'ICommand')

If I change the binding of the SavedBook user control in the list view's item template to MoreButtonClickedCommand in ManageBooks.xaml and it's corresponding ICommand in the code behind (xaml code below), the error goes away but clicking the button still does not call the code behind's OnSavedBookMoreButtonClickedCommand() method.

<local:SavedBook
    BookName="{Binding Name}"
    MoreButtonClickedCommand="{Binding DataContext.MoreButtonClickedCommand, ElementName=SavedBooksListView}"/>

I'm guessing that I am confused about what the actual data context of the SavedBook user control is. Using Snoop, it shows the SavedBook's DataContext as a Book object and the ManageBooks's DataContext as ManageBooks.

I'd be so appreciative if anyone might have any ideas of how I can track down this binding path error or might see what I'm missing. TIA!

8 Comments
2024/05/04
14:03 UTC

3

PDF Generation using QuestPDF in ASP.NET Core — Part 1

Report generation in an enterprise setting provides insights into key performance indicators, tracks progress toward goals, and helps stakeholders make informed decisions.

By the end of this article, you should be able to generate a dummy investment advice using QuestPDF

Read article here

0 Comments
2024/05/04
13:14 UTC

1

AggressiveInlining and guard clauses

I had a method in my codebase that was marked to be inlined if possible using the MethodImplAttribute.

The method also had a guard clause with a return statement at the very beginning of the method, like so:

[MethodImpl(MethodImplOptions.AggressiveInlining)]
void Method(bool condition)
{
    if(!condition)
    {
        return;
    }

    DoSomething();
}

This got me wondering: is the compiler actually smart enough to automatically invert the guard clause, or do I need to avoid guard clauses like this inside methods that I want to be inlined?

[MethodImpl(MethodImplOptions.AggressiveInlining)]
void Method(bool condition)
{
    if(condition)
    {
        DoSomething();
    }
}
24 Comments
2024/05/04
11:28 UTC

0

Books when coming back to C#

Hey all, I’ve been a long time user of C# (10ish years) but have never dived in deep. I just got a new role as a C# developer, and I’m wanting to understand the language more. Anybody have book recommendations targeted towards current C# devs, who have experience in other languages, to better understand how to use the build chains and language features?

4 Comments
2024/05/04
08:22 UTC

0

Been out of development for 2 years - what are some things I’ve missed?

Before I took a break for mental health reasons 2 years ago I was a C# developer of 12 years and considered myself an expert. I’m only now getting back into things and I’m wondering what major developments/changes have been made since?

Thanks!

33 Comments
2024/05/04
08:10 UTC

82

I've been slowly learning this language for almost three months now. How can I still improve upon this Tic-Tact-Toe code? GitHub link in comments.

85 Comments
2024/05/04
03:08 UTC

13

Methods, Funcs & Actions...Oh, My!

11 Comments
2024/05/04
01:08 UTC

1

MAUI/WPF Architecture Advice

I'm a well seasoned C# developer mainly working on ASP.NET and WinForms, I have dabbled in Xamarin.Android too (not Forms). My use of XAML and MVVM is limited (outside of the usually ASP MVC style of MVVM).

I am looking to move some of my apps away from WinForms to MAUI with the hopes to make the cross compatible with macOS.

I am just struggle to understand how I should be using the View and ViewModels in the way I need.

I basically have an app that reads in multiple files into an object (got a "framework" class library that outputs all as List<T>) Once these files are all read in a handful are combined together. Due to the size I really need to do this process all in one go.

Once I have the objects in the state I want I then want to display them as "tabs" or "views" in the app with items being clickable and editable. I think I will need some type of IPropertyChange event, which I current do do in the WinForm App

I am just wondering that if I am doing the initial load/build this should naturally create different "views" but can I, or should I, be creating and populating views from the parent, or should I just have one big view/viewmodel and just use a tab controller or something? How should I be splitting this up to fit in with the MVVM practices and making sure I utilise XAML for what it is.

8 Comments
2024/05/04
00:16 UTC

0

public class IntListener<X> where X : Action<int>

Hey!

my AI tells me this is not something that has been suggested yet.

This is of course a listener class, which listens to changes of a Property declared elsewhere but which for instance updates the text field of a graphical component in a web page or a Unity game such as

public class Account {
  public static Action<int> CreditsChanged;
  public int CreditsValue = 10;
  public int Credits { get { return CreditsValue; } set { CreditsValue = value;     CreditsChanged.Invoke(value); }
}

so i can create a class IntListener<Account.CreditsChanged>

which would be smacked on every field which needs to listen to the event.

Or am I making no sense?

11 Comments
2024/05/03
22:14 UTC

0

C# books, thoughts?

Just curious as to people's thoughts on books. I see lots of posts of people asking and recommending books on C#. I've personally just done everything online, on the job, and working with peers. I feel pretty up to scratch with things (but you don't know what you don't know!). So just wondering do people feel these books are worthwhile? What have you learnt that you haven't on the job or through experience?

10 Comments
2024/05/03
21:09 UTC

1

Control TV Samsung with http request

Hi everyone, I'm trying to integrate the Samsung TV api into C# via http requests. I'm currently testing with Postman and I'm stuck with a 402 error trying to make this POST:

POST /RenderingControl HTTP/1.1 Host: 192.168.223.152:9197 Content-Type: text/xml; charset="utf-8" SOAPACTION: "urn:schemas-upnp-org:service:RenderingControl:1#GetMute" : Content Length: 395

<?xml version="1.0" encoding="UTF-8"?>

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"> <s:Body> <u:GetMute xmlns:u="urn:schemas-upnp-org:service:RenderingControl:1"> <InstanceID>0</InstanceID> <Channel>Master</Channel> </u:GetMute> </s:Body> </s:Envelope>

could you help me solve this?

14 Comments
2024/05/03
19:54 UTC

3

Cross Platform (win/Linux) Gui

I'm out of touch with .Net.

What's the go to for cross platform gui dev?

Is there anything? Like, visually design in VS2022 and run on Linux and windows?

Did Microsoft pull that off yet?

6 Comments
2024/05/03
18:40 UTC

1

Null when attempting to set property object to another object

This is WinUI 3 if it matters.

The following is part of my UserControl class:

public Models.Item SelectedItem { get; private set; } = new();

private void Item_Changed( object sender, EventArgs.ItemChangedEventArgs e ) {
    this.SelectedItem = e.Item
}

When this event fires, the result of this.SelectedItem is null, even though e.Item is not. e.Item is also of type Models.Item.

What am I doing wrong here?

Edit:

When this.SelectedItem is already null, it works. But when editing an item and this.SelectedItem and e.Item are the same, I get null.

4 Comments
2024/05/03
16:07 UTC

Back To Top