/r/learncsharp

Photograph via snooOG

Learn C# is about learning C#! Post your questions regardless of your experience level.

Welcome to /r/LearnCSharp!

Please read the rules and guidelines below and search before posting.

Rule 1: Posts must be about learning C#.

Rule 2: No posts advertising blogs, videos, or tutorials. If you'd like to make such a post here, ask the moderators.

Rule 3: No posts that are recruiting or hiring, but looking for buddies or mentors is fine.

Rule 4: Be polite, constructive, and serious -- make sure your answer isn't a joke or mocking the questioner.

If you make a post here, you must engage with the people who answer you. Tell them it worked, tell them it didn't, ask for clarification. Do not delete your post after you get an answer! Leave it up so others might find it an learn, or continue the conversation.

To get the best help, make sure you ask a complete question. "I'm stuck" isn't actionable. Posting your assignment or naming a goal isn't good enough, either. No screenshots -- format your code using four spaces on every line so that Reddit will format the whole block as code.

The site-wide rules always apply!

/r/learncsharp

19,221 Subscribers

1

Electron to webview2 which UI

Hello

I'm thinking of replacing a small electron app of mine, and Webview2 seems to be the best alternative.

What would be the best UI to run a webview2 app, Winforms, WPF, ..?

Thanks

3 Comments
2024/11/02
18:55 UTC

3

how do you simulate incomplete tcp data in unit tests

I'm trying to learn about buffers, and TCP handlers in Kestrel.

The way i'm doing this is by implementing a very basic message broker based on the STOMP protocol.

So far i've been parsing frames correctly, when unit testing, but when actually receiving TCP traffic, i should be able to handle incomplete data, and i'm not sure how i can simulate this behaviour in unit tests. Does anyone have examples of unit tests for Microsoft.AspNetCore.Connections.ConnectionHandler ?

This is what i have so far:

public class StompConnectionHandler(ILogger<StompConnectionHandler> logger, IStompFrameParser frameParser)
    : ConnectionHandler
{
    public override async Task OnConnectedAsync(ConnectionContext connection)
    {
        logger.LogDebug("Connection {ConnectionId} connected", connection.ConnectionId);
        var input = connection.Transport.Input;
        while (true)
        {
            var result = await input.ReadAsync();
            var buffer = result.Buffer;
            if (frameParser.TryParseFrame(ref buffer, out var frame))
            {
                // TODO: process frame
                logger.LogDebug("received frame {@Frame}", frame);
            }

            input.AdvanceTo(buffer.Start, buffer.End);
            if (result.IsCompleted)
            {
                break;
            }
        }

        logger.LogDebug("Connection {ConnectionId} disconnected", connection.ConnectionId);
    }
}
public class StompFrameParser(ILogger<StompFrameParser> logger) : IStompFrameParser
{
    private ref struct Reader(scoped ref ReadOnlySequence<byte> buffer)
    {
        private readonly ReadOnlySpan<byte> _frameTerminator = new([(byte)'\0']);
        private readonly ReadOnlySpan<byte> _lineTerminator = new([(byte)'\n']);
        private readonly ReadOnlySpan<byte> _carriageReturn = new([(byte)'\r']);

        private SequenceReader<byte> _sequenceReader = new(buffer);

        public bool TryReadToNullTermination(out ReadOnlySequence<byte> sequence)
        {
            return _sequenceReader.TryReadTo(out sequence, _frameTerminator);
        }

        public bool TryReadToLf(out ReadOnlySequence<byte> line)
        {
            return _sequenceReader.TryReadTo(out line, _lineTerminator);
        }
    }


    public bool TryParseFrame(ref ReadOnlySequence<byte> buffer, out StompFrame? frame)
    {
        var reader = new Reader(ref buffer);

        if (!reader.TryReadToLf(out var command))
        {
            frame = default;
            return false;
        }

        var commandText = Encoding.UTF8.GetString(command).TrimCrLf();
        Dictionary<string, string> headers = new();

        while (reader.TryReadToLf(out var headerLine) && Encoding.UTF8.GetString(headerLine).TrimCrLf().Length != 0)
        {
            var header = Encoding.UTF8.GetString(headerLine).TrimCrLf();
            var headerParts = header.Split(':');
            if (headerParts.Length != 2)
            {
                logger.LogError("Invalid header: {Header}", header);
                frame = default;
                return false;
            }

            var key = headerParts[0];
            var value = headerParts[1];
            headers.TryAdd(key, value);
        }

        if (!reader.TryReadToNullTermination(out var body))
        {
            frame = default;
            return false;
        }

        var bodyText = Encoding.UTF8.GetString(body).TrimCrLf();

        frame = new StompFrame(commandText, headers, bodyText);
        return true;
    }
}
public class StompFrameParserTests
{
    private static ReadOnlySequence<byte> CreateReadOnlySequenceFromString(string input)
    {
        byte[] byteArray = Encoding.UTF8.GetBytes(input);
        return new ReadOnlySequence<byte>(byteArray);
    }

    [Fact]
    public void ParsingCorrectFrame_ShouldReturnFrame()
    {
        var logger = Substitute.For<ILogger<StompFrameParser>>();
        var parser = new StompFrameParser(logger);

        var sb = new StringBuilder();
        sb.AppendLine("MESSAGE");
        sb.AppendLine("content-type:application/text");
        sb.AppendLine();
        sb.AppendLine("Hello World");
        sb.Append('\0');

        var buffer = CreateReadOnlySequenceFromString(sb.ToString());

        Assert.True(parser.TryParseFrame(ref buffer, out var result));
        Assert.NotNull(result);
        Assert.Single(result.Headers);
        Assert.Equal("application/text", result.Headers["content-type"]);
        Assert.Equal("Hello World", result.Body);
        Assert.Equal(StompCommand.Message, result.Command);
    }
}
1 Comment
2024/10/30
16:13 UTC

2

MVVM tips or experience with big apps

I would like to learn WPF or Avalonia with the famous MVVM pattern and I have finally understood how it works with the INotifyPropertyChanged however all the starting examples are very basic.

So I have also seen that there is the Community MVVM Toolkit which saves a lot of work and I have tried it and it is fascinating. I have also seen that many Avalonia examples use ReactiveUI which looking at it from above is a bit more complicated.

Now the question of the matter is, large and complex applications with many classes, models, options, sub-options and user configurable parameters are really handled with MVVM, I ask this because just to create a simple booking application with Singleton Sean (Youtuber) has created me many files and high complexity.

I usually develop with Blazor and API and it is not that complex. I still don't consider myself a very experienced developer but I would like to learn about MVVM to expand my knowledge.

I would like to hear testimonials or opinions from people who have worked on large desktop applications with this pattern or who can give me recommendations for reading or videos.

PS: Singleton Sean's channel has a lot of valuable content.

5 Comments
2024/10/30
10:23 UTC

0

I want to vent :(

I want to vent and say it is miserable to learn c# in the start.

It feels like learning a new game. I dont know anything. It feels frustrating to know new stuff. I feel down if things have errors and if things dont work.

I was doing while loop ( FirstAnsw < 1 || FirstAnsw > 2 ). It's not working and it it is not recognizing the method I put underneath it. I keep thinking about it for a week now.

Honestly, It's just a struggle. But it is fun but man it just brings you down if nothing works and it just becomes a mess.

Yeah I have no Com sci degree or training. I just want to build some fun games or apps for trolling like your mouse dissapearing or freezing while you use it hahaha

19 Comments
2024/10/30
09:14 UTC

6

What is "do" syntax?

Sorry for the bad grammar.

I was watching a someone create an interaction game and saw him using this.

I find it amazing because it made his code a lot cleaner and more organize because he just group it up using this syntax.

```

//int

int choice;

//strings

string Class;

//Class Creation

do

{

Console.Clear();

Console.WriteLine("Please choose a class below");

Console.WriteLine("Warrior");

Console.WriteLine("Mage");

Console.WriteLine("Your choice");

Class = Console.ReadLine.ToUpper();

if ( Class == "WARRIOR" ) || (Class == MAGE )

{

choice = 1

}

else {}

}

while ( choice == 0 );

choice = 0;

```

* I just realize it's a form of Loop syntax. Let me know if I am wrong and if you have any more recommendations let me know thanks!

20 Comments
2024/10/27
07:35 UTC

3

python intermediate just learning c#

I may have a use case to need some C# code an I've only been doing basic python stuff for 3 years. But I do know the python fundamentals quite well. I just saw some code of what I need to do and don't understand the public void vs static void stuff.

Is there a video for a python convert where someone can wipe my diaper and babysit me into understanding what the hell is going on with all this additional nonsense? Thanks.

4 Comments
2024/10/26
00:49 UTC

2

How do y'all handle 2FA? WebApp (SPA) with React front end & WebAPI backend

Currently basing things off the IP the user last logged in from but users are complaining it is happening too often.

0 Comments
2024/10/25
15:55 UTC

1

How to find out the table height & width in PDF Sharp libraries?

I am using below library to generate PDF report.

  1. PDF Sharp
  2. MigraDoc.DocumentObjectModel

In runtime I am generating table with dynamic content, I want to find out width and height of the table in runtime.

Can anyone help?

1 Comment
2024/10/25
03:50 UTC

0

How do you guys remove this?

There's an annoying Display box blocking my code

it says

// Tab to accept

2 Comments
2024/10/23
19:55 UTC

0

How can I convert my list<string> to a string[ ] array?

I am trying to write a simple code that will print out some names alphabetically but I wanna do it using a list.

I know that Array.Sort(); exists but I couldnt find a way to convert my list to an array.

using System; using System.Collections.Generic;

namespace siniflistesi { class Program { static void Main(string[] args) { Console.ForegroundColor = ConsoleColor.DarkCyan; Console.WriteLine("12-A sinif listesini gormek icin herhangi bir tusa basiniz."); Console.ReadKey(); Console.Clear();

List<string> yoklama = new List<string>(); string[] thearray = new string[yoklama.Count]; yoklama = Convert."i couldnt find an array option here" (thearray); Array.Sort(yoklama);

yoklama.Add ("Nehir"); yoklama.Add ("Zumra"); yoklama.Add ("Elif");

for (int i = 0; i < yoklama.Count; i++) { Console.ForegroundColor = ConsoleColor.DarkGreen; Console.WriteLine(yoklama[i]); } Console.ReadKey(); } } }

15 Comments
2024/10/23
13:06 UTC

0

Relocation job interview

Hi tech experts,

I have scheduled an interview with Malaysian company which is offering me relocation opportunity. I have 4+ years of experience as a dotnet developer.

I want to ask to experts those who cracked that type of opportunities before. please give me resources ( concepts to prepare) to crack that interview. Where should I prepare?

1 Comment
2024/10/21
21:35 UTC

6

Trying new projects that can teach me a lot

Hello everyone,

I'm teaching myself programming and have a few questions about what I should focus on learning next. Here's where I'm at so far:

  • I can create and understand console and WPF applications without too much difficulty.
  • I have some basic knowledge of SQLite.
  • I have a decent grasp of OOP (Object-Oriented Programming). I understand most of what’s covered on basic OOP tutorials (like W3Schools).
  • I’ve tried Unity for a while and understand how components and code interact within a game scene.
  • Participated in two gamejams. (https://lukasprogram.itch.io/)
  • I know a little bit of LINQ.

When I look at larger projects on GitHub, I often have trouble understanding what’s going on. I’d appreciate your thoughts on what I can learn to improve. For example, I’m not very confident about events—are there any good projects I could try that use events?

I’m not particularly interested in web development at the moment, although I’m curious about backend development and might explore it one day.

By the way, I’m a 15-year-old student and have taught myself everything through trial and error. Any feedback or suggestions would be really helpful! Thank you!

4 Comments
2024/10/21
19:20 UTC

0

Could Microsoft VS damage my Laptop?

Hi guys Im trying to learn C# cause Im bored and Im trying to stay away from Dota for a while hahaha.

Im just worried that it could cause damage like continuously ran in the background of my laptop without me noticing even if I close it down.

I know its a stupid question, please forgive me haha. Im just worried cause I only have 1 of it.

16 Comments
2024/10/21
18:00 UTC

0

.NET Identity, do I have to use EF?

Every tutorial I find uses EF but I kind of prefer (I think its called ADO?) and stored procedures.

6 Comments
2024/10/20
20:29 UTC

3

I have a WebAPI, the "front-end" is written in React by another person. What is the best way to secure the WebAPI so outsiders can't run Get/Post commands?

Would it be JWT?

Any good tutorials (or AI prompts) to teach me how to implement?

thanks!

18 Comments
2024/10/17
21:32 UTC

0

[WinForms] Need help optimizing custom controls creation/updating of ui

I have custom controls that is being dynamically created based on data from several API calls. These controls are being created after the processing of data is finished. There were no issues from API calls/mapping of data since I can see that the custom controls are being created immediately after opening the form but the problem is updating the data on the UI. It takes several seconds for the UI to get updated and it gets slower the more controls there is. I have used SuspendLayout/ResumeLayout/PerformLayout before for updating a certain Custom Control, but I want to increase the speed on how the UI gets updated.

This is the flow:

  1. Click button to open the form

  2. Parent Form gets created and creates some other UI control

  3. Parent Form displays and proceeds to create the custom controls (at this point, the "base" custom controls are already created, however the data still needs to get updated. The data are the scribbles in the drawing, it's just a bunch of text)

  4. Each custom control will be updated based on the data. Each custom control's size are dynamic and will depend on how long the texts are. (This is what I want to optimize, it takes several seconds to get updated and it increases depending on the number of controls/height of controls)

1 Comment
2024/10/17
10:19 UTC

2

Winform Pokedex App

Hi!

I have picked up C# in the last week or so and looking some feedback on my first WinForm application.

It is a Pokedex app that uses pokeapi.co to get information on Pokemon and present it to the user.

Next steps are tests and error handling, but any feedback would be great!

Link: https://github.com/cwilmott0323/PokedexApp/tree/master

3 Comments
2024/10/17
00:04 UTC

3

Can I ask for advice

For the moderators please let this post pass, let me know what can I do to not get removed.

Might be a long post but hopefully, you can still read it.

Ok, I would like to ask an advice for people who are working as a software developer.

-What does a normal job look like as a developer? -I'm assuming it is a team effort how do you do it as a team? Do you just pick that ok I'm gonna do this part? -Do you also have political drama there? What's the worse situation you ever had in your job? -I dont have a degree in CS, how likely am I to get a work of worse to get bullied if ever I passed?

  • A little background to me. I graduated with a BS degree in some Allied health profession. I'ce been working a lot now and I realize I cant bear it. I have severe OCD and I constantly take a lot of sick leave or sometimes if I really need to work I just have mental breakdown to the point of crashing down. Even with therapy it is hard.

Working in healthcare is really stressful, a lot of politics, drama, and worse is the on calls and night shifts.

I want to know what is a daily life in your job as a developer so that Im prepared or expected to know what is gonna happen.

My goal is probably 5 (If. I get lucky ) or 7 yrs of learning c# before I decide to change my career. I think life is harsh but It's also my fault for not pursuing the career I wanted.

Why I chose C#? I spent my life in the computer and playing games a lot. I wanted to customize my own desktop to look cool or edgy hahaha. Dont know if this is the right language for me.

But yeah, people here are very nice and hope I can hear from you guys if I am making the right decision haha.

14 Comments
2024/10/15
22:22 UTC

3

Change SolidBrush colour based on values within object - WinForm

Hi,

I am new to C# and I am trying to set the colour of some circles based on the values of data within an object.

I have the following Class:

public class Monster {
    public int Stat1 {get; set;}
    public int Stat2 {get; set;}
    public int Stat3 {get; set;}
}

Within a Method of my Form Class I set the Values for stats 1,2,3:

namespace Game
{
    public partial class MonsterModel : Form
    {
        public PokedexModel(string pokemon, List<PokeAPI> p)
        {
            InitializeComponent();
        }
        private async void PopulateData(string name)
        {
            Monster m = new Monster();
            m = LoadStats(name);
        }
    }
}

From here I can access the stats by calling m.Stat1 etc.

Now I have the following three Labels using the Paint event:

        private void label1_Paint(object sender, PaintEventArgs e)
        {
            SolidBrush solidBrush = new SolidBrush(Color.FromArgb(0, 0, 0, 0));
            e.Graphics.FillEllipse(solidBrush, 0, 0, 30, 30);
        }
        private void label2_Paint(object sender, PaintEventArgs e)
        {
            SolidBrush solidBrush = new SolidBrush(Color.FromArgb(0, 0, 0, 0));
            e.Graphics.FillEllipse(solidBrush, 0, 0, 30, 30);
        }
        private void label1_Paint(object sender, PaintEventArgs e)
        {
            SolidBrush solidBrush = new SolidBrush(Color.FromArgb(0, 0, 0, 0));
            e.Graphics.FillEllipse(solidBrush, 0, 0, 30, 30);
        }

What I would like to be able to do is something like this:

        private void label1_Paint(object sender, PaintEventArgs e)
        {
            if (m.Stat1 < 100)
            SolidBrush solidBrush = new SolidBrush(Color.FromArgb(255, 255, 0, 0));
            e.Graphics.FillEllipse(solidBrush, 0, 0, 30, 30);
        }

I have a couple of ways of doing this.

Option 1 - Instantiate m at a higher level:

namespace Game
{
    public partial class MonsterModel : Form
    {
        Monster m = new Monster();
        public PokedexModel(string pokemon, List<PokeAPI> p)
        {
            InitializeComponent();
        }
        private async void PopulateData(string name)
        {
            m = LoadStats(name);
        }
    }
}

Option 2 - Update PopulateData():

        private async void PopulateData(string name)
        {
            m = LoadStats(name);
            if (m.Stat1 < 100) {
            label1.Paint += (sender, e) =>
            {
                SolidBrush solidBrush = new SolidBrush(Color.FromArgb(255, 255, 0, 0));
                e.Graphics.FillEllipse(solidBrush, 0, 0, 30, 30);
            };

            label1.Invalidate();
        }
}

Is there a better way of doing this?

4 Comments
2024/10/14
01:49 UTC

2

How to crop the image in C#?

I am having one big image and it has so many small images in it.

Example: several birds images are there in one big image.

I need to crop this into multiple images and save it in separate image using image recognizing concept.

How can I achieve this?

Your response will be big help for me

3 Comments
2024/10/09
16:58 UTC

0

To use "Github Copilot," do I need to be proficient with GitHub?

I know GitHub really something I should learn, and is on my to do list, but I am curious if not know it, will Copilot be a waste of money?

2 Comments
2024/10/08
15:24 UTC

0

Issue in creating PDF with PDFSharp library in C#

I am using below libraries to create PDF report with custom font family in C#.

  1. PDFSharp
2. MigraDoc

While generating report in English with "Nunito Sans" font it is perfectly fine. But in Chinese, Japanese, French it is not working.

Can any one give some insights?

3 Comments
2024/10/07
04:38 UTC

0

Give me your learning experience

Hey everyone, I’m learning c# to get into game development. I’ve dedicated my days and most nights to doing this. Ive purchased a class on Udemy and have been making great success. I’m truly falling in love with it and even making such simple programs have gave me a feeling like nothing else.

With all this said I have gotten to a point in the course where things feel like they have increased in difficulty (which I expected) and by that I mean it takes a lot longer to understand what’s being taught. I rewatch lectures over and over and look to different examples to just try and understand. I’m starting to get discouraged with how hard things are becoming because I almost feel like I’m not smart enough to get it.

Don’t get me wrong I totally understand that learning anything new is difficult but I’d like to hear about your journeys and if you ever felt like this at some point as well!

Also I just want to add that I have no intentions of stopping my learning in case this post sounded like that. This post is just to share my experience so far and get other people’s experiences while learning as well!

Thanks for taking the time to read this as well :)

8 Comments
2024/10/06
21:26 UTC

6

C# players guide

I bought this book to get acquainted with C#. I am running Ubuntu as my OS. Is VS code adequate to allow me to learn learn C# ?

15 Comments
2024/10/04
14:05 UTC

5

I need a tutor for a C# course

Hello everyone and thanks for taking the time to read this. I’m currently taking a C# Full Stack Developer course and I’m halfway through and I need help. My course is video based and my teacher isn’t the easiest to get in contact with so I feel alone on a island with no help. I would greatly appreciate any advice about tutoring that would allow me to interact with someone with professional experience. Again thanks for your time and please let me know if you can help.

4 Comments
2024/10/03
20:39 UTC

8

Where do I continue learning?

Hello! Do you guys have good learning spots? As of right now I know the basics of classes and methods ,(constructors, objects, abstract, inheritance and etc) I finished the w3 school tutorial and watched a 4 hour bro code tutorial. I also learned through an online course the basics. So, where do I continue my learning?

8 Comments
2024/10/02
20:11 UTC

2

Long existing task disappears after some time

I have a docker containerized ASP.NET application which runs hourly integration work mainly collecting data from one web url and sending it to another. In my program.cs I have set it to hosted service:

builder.Services.AddScoped<ICPoller, CPoller>();

builder.Services.AddHostedService<CPoller>();

And then the implementation itself is:
protected override async Task ExecuteAsync(CancellationToken stoppingToken)

{

var CleaningTask = CleanUp();

var CollectorTask = StartCollectors();

try

{

await Task.WhenAll(CleaningTask, CollectorTask);

}

catch (Exception ex)

{

Console.WriteLine(ex.Message);

}

}

Both the CleanUp and StartCollectors are pretty much like this:

while (true)

{

try

{

do stuff

await Task.Delay(TimeSpan.FromMinutes(45));

}

catch (Exception ex)

{

Console.WriteLine(ex.Message);

}

}

This works fine for some time but not even complete month. There are no traces of exception, nothing. The tasks just silently stops working. What should I do to find out why the tasks just suddenly die?

1 Comment
2024/09/29
16:28 UTC

1

Syntax Question

Hi, I come from a VB background. I have recently had an idea for an app that would really help my company, so I decided to start writing it in C# as my use case negates using VB anyway.

Having never used C#, I am finding some of the syntax and concepts a little confusing. In VB, if I wanted to have a button which opened another form, I would just use form1.Show() But now I need to do form1 f1 = new form1() and I don't understand what each part of that statement is for.

Is there a resource I can reference that will help me transfer what I know in VB to C#?

8 Comments
2024/09/24
21:27 UTC

0

[Noob] What's an efficient way to check neighbors around a cell in a 2D array?

Hello, as title says I'm looking for an efficient way to check sorroundings of cells in a 2D array, but I have to do that in 3 different ways:

circle of 8 circle of 12 2 adjacent cells from all sides

For now my only idea is to create 3 different methods with hard coded offsets in an array (similar to one below), iterate over it and collect neighbors in a list

int [.] directions = new int [, {-1, -1}, {-1, 0}, {-1,1} ... .... etc]

Looking for suggestions.

8 Comments
2024/09/23
23:49 UTC

2

Handling EF models when moving code to separate library

Let's say we want to move some code to a separate library since we want to reuse it in multiple projects. The code has a dependency on the big monolithic data model that we obviously can't bring along.

What's the best practice of designing a library like this, assuming that we don't want to create a new dbcontext in it and want to let the implementing project define entities in its own DbContext? I'd like to use the dbcontext defined in the "parent" since they could have some custom logic surrounding the dbcontext properties, saving, initialization etc. that I can't anticipate in the class library.

My first thought is to just code to interfaces - if this library used to work with the Comment data model, now we'll code everything to IComment instead. When some project references this library it would have to make its Comment data model implement the IComment interface and map its properties to it.

Would this actually work with entity framework (core)? Can we even have DbSet<IComment>, or a way to map DbSet<Comment> to DbSet<IComment> or would this require a lot of manual hacking? Now that I've typed this out I guess I need some kind of a dependency injection but on the dbContext level, take only some of the DbSets from a 'master dbcontext' and inject it into the library's required smaller dbcontext of interfaces?

6 Comments
2024/09/23
09:25 UTC

Back To Top