/r/learncsharp
Learn C# is about learning C#! Post your questions regardless of your experience level.
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
I have a WPF window that opens to choose a COM port when a port has not been previously selected. Once a port has been selected the window sets the com number and closes. The WPF window has been proven to work by itself and added it to my program.
It is called by a separate class with:
Task commy = Commmy.Selected();
Task.Run(async() => await Commmy.Selected());
WinForms.MessageBox.Show("done waiting");
I have a message box at the end of the task Selected() and after the await as a "debug". These will not exist in the final code.
From what I understand Show() is a normal window and ShowDialog() is modal window.
I am using a ShowDialog() to prevent the method from finishing before I close the window(only possible once a COM port has been selected) however the message box at the end of the method opens up the same time as the window opens. The await is working because the "done waiting" message box will not open until I close the "at end of selected" message box. This tells me that the ShowDialog is not working as I intended (to be blocking) and I don't know why.
Here is the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
namespace ComSelectionClass
internal class Commmy
{
static MainWindow mainWin;
public static Task Selected()
{
Thread thread = new Thread(() =>
{
MainWindow mainWin = new MainWindow();
mainWin.ShowDialog();
mainWin.Focus();
mainWin.Closed += (sender, e) => mainWin.Dispatcher.InvokeShutdown();
System.Windows.Threading.Dispatcher.Run();
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
System.Windows.Forms.MessageBox.Show("at end of selected");
return Task.CompletedTask;
}
}
Any help to block my code until the window is closed would be appreciated.
Hi. Given a string lists of paths (every path always contain at least one folder), I must generate a TreeView structure where the root nodes are the paths, except the last folder which is displayed as a child node if it's not a root folder. Basically display as much as possible from the path where it doesn't have subfolders.
I need this for a specific file manager kind of app I'm developing.
For instance, from these paths:
c:\Music
d:\Documents
e:\Test\Data\Test 1
e:\Test\Data\Test 2
e:\Test\Data\Test 3
e:\ABC\DEF\XYZ\a1
e:\ABC\DEF\XYZ\a1\c2
e:\ABC\DEF\XYZ\a2
e:\ABC\DEF\XYZ\b1
it should generate something like...
_c:\Music
|
|_d:\Documents
|
|_e:\Test\Data
| |_Test 1
| |_Test 2
| |_Test 3
|
|_e:\ABC\DEF\XYZ
|_a1
| |_c2
|_a2
|_b1
Still a newbie and would like to ask when do you guys decide to ask help? or look at google?
I'm trying to build like a clock at the moment and trying to build it without looking in google or looking at other people's work.
Currently. I'm losing and my brain hurts xD
EDIT: Thanks to all of the people who answered here. I never thought that usingngoogle is just fine, I thought I was cheating or something, hahah.
Context: User fills in a form on my webpage. User then saves the form, based on the filled in data the form can get the following states:
States:
public enum State
{
[Description("NewForm")] // Initial state
Draft = 0,
[Description("Denied")]
Afgekeurd = 1,
[Description("Approved")]
Afgerond = 2,
[Description("WaitForApprovalManager")]
WaitForApprovalManager = 3,
[Description("WaitForApprovalTech")]
WaitForApprovalTech = 4,
[Description("WaitForApprovalFinance")]
WaitForApprovalFinance = 5,
}
How I implemented the State Machine Pattern:
FormStateService.cs:
public class FormStateService
{
private FormState _currentState; // Current state of the form
private Form _form; // Form that the user filled in
public FormStateService(Form form)
{
_form = form;
if (_currentState == null)
{
SetState(new DraftState()); // Set initial state to draft
}
}
public void SetState(FormState state)
{
_currentState = state;
_currentState.SetContext(_form);
}
public Form HandleStateTransition()
{
_currentState.HandleStateTransition(this);
return _form;
}
public Status GetCurrentState()
{
return (State)_form.State;
}
}
FormState.cs:
public abstract class FormState
{
protected Form _form;
public void SetContext(Form form)
{
_form = form;
}
public abstract void HandleStateTransition(FormStateService stateMachine);
}
WaitForApprovalManagerState.cs
public override void HandleStateTransition(FormStateService stateMachine)
{
if (_form.TotalReceipt >= 500) // Wait for managed to approve
{
_form.State = (int)Status.WaitForApprovalManagerState;
stateMachine.SetState(new WaitForApprovalManagerState());
return;
}
if (_form.TotalReceipt >= 500 && _form.ManagerApproved && _form.TechForm == true) // If manager has approved let tech approve
{
_form.State = (int)Status.WaitForApprovalTechState;
stateMachine.SetState(new WaitForApprovalTechState());
return;
}
}
I have a Generic class: MyClass<T> where T is IGameElement.
I also have a class named Player.
I am getting into events and I am having a hell of a time here.
there is a third class that is running my program, it is sort of the programs Main. For this troubleshooting, lets call it Main.
There is an instance of MyClass in Main, and there is a Player class in Main.
I need the Player class proper, to be able to subscribe to the MyClass event, handle the event, then unsubscribe to that same event. I have tried everything and I am bashing my head against the wall. Reflection, Dynamic, etc... The problem I am having is that I need the Player class to not care about MyClass's type. Unless I am getting something wrong here, that is what I cannot seem to do.
Anyone want to walk me through what I need to do to get this behavior?
Hey everyone! I am learning to start processes(.exe's) using C# and so far the debugging experience has been great! I am trying to create a Windows Service that is constantly running in the background checking if 3 processes are running! If for some reason these processes stop, I try to launch them again!
I have had some issues tho- for some reason when I start the executable, the GUI of the program won't show up! The process is created! I can see it running in task manager, but for some reason the program does not start the same way as if I have clicked on it!
After doing some research around, I saw that you have to specify the working directory of your process! Something like this:
using(Process p = new Process())
{
p.StartInfo = new ProcessStartInfo(myObject.ProcessPath);
p.StartInfo.WorkingDirectory = Path.GetDirectoryName(myObject.ProcessPath);
p.Start();
}
_logger.LogWarning($"Starting {device.ProcessPath} at {Path.GetDirectoryName(device.ProcessPath)}");
This did the trick for me in debugging mode! It starts off the process nicely- The GUI shows up and everything works as it is supposed to. But when I try to publish my service, the processes go back to not starting the same way anymore! Do you guys think it might be Visual Studio messing up the program? The publishing options look something like:
Configuration --> Release|Any CPU
Target Framework --> Net 8.0
Deployment Mode --> Self Contained
Target Runtime --> win-x64 (I changed this! it used to be x86... is there a con to using x86?)
Produce Single File --> Yes
Enable ReadyToRunCompilation --> Yes
I am sorry for adding bold letters to the top ;w; I really hope someone can help me- I am completely lost and I feel like big wall of plain text will turn people away :(
It's weird because singular SelectedItem isn't readonly.
I'm been learning memory management since yesterday and from what I understood it's best if you where to use arrays or tuples something that you can give them value as a group.
Im just curious whether you guys have your own way of managing it? Like in your own style?
Im just a newbie so forgive me if I wrote something wrong here. Thanks!
Hi,
I'm looking for some architectural advice. I'm working on a small side project solo. I'm not a professional programmer.
I made a simple front end to a linear optimizer engine to build up a model with various constraints, run the optimizer, then print out the data. I'm transitioning the front end from hard coded in console to a WPF app. I want to have several various types of rules that can be selected by the user with custom input, then, when the user input is all collected, the user clicks a button to run the optimizer.
I made a ListBox to display the various user added rules, and a Frame to display the input page for the rule. Each rule type needs a different page displayed in the frame to collect the input for that particular rule type.
I'm thinking each rule should be an object, and there should be a collection, like a list that contains all the rules. Each rule object should implement an interface with a method that loads the rule into the optimizer model, so that when the optimizer is run, I can just iterate the list and call that function for each rule. Each rule should also implement a function to return it's user input page to load it into the frame when selected from the ListBox list.
I think this should work, but I'm wondering if I'm missing an idiomatic way to do this.
I'm just curious cause you got arrays or tuples. In what situation do you use enumerations?
Edit: Sorry guys I didn't elaborate on it
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!
Both main form and the small form have black backgrounds. Main form includes a videoview and the small form includes a borderless textbox with black background. When the small form is displayed over the main form, sometimes there is a white flicker visible for a few milliseconds, like the system is trying to paint them in white and then it quickly changes the colors to black. How to stop this GDI+ annoyance?
I tried setting either one or both forms to DoubleBuffered and still the same result.
int[] scores = new int[3] { 1, 2 , 5 }; //How to display or make it count the 3 variables?
foreach (int score in scores)
Console.WriteLine(scores); // I want it to display 1,2,5
I already kinda know coding and C#. But when it comes to "how to structure a classes", "private/public/protected etc." and etc. , i just lost, i have no idea what to do.
TLDR: I know coding, but not programming.
Hey,
I've been learning ASP.NET Core for the last couple weeks (coming from Express.js / JS), and at first I started doing my projects with the "N-Tier" architecture, which made a lot of sense right away.
Now, I'm trying to learn different architectural styles, starting with "Clean architecture".
I was trying to "convert" my existing project (made with n-tier architecture) to use clean architecture... but it feels really un-intuitive and needlessly complex to write with clean architecture.
I'd like your opinion on the structure of my project for both n-tier and clean architectures, and any tips on learning clean architecture.
N-Tier Structure:
AppName.API/
Controllers/
AppName.Business/
DTOs/
Filters/
Services/
Validators/
AppName.Data/
Contexts/
Migrations/
Models/
Repositories/
Implementations/
Interfaces/
N-Tier Dependencies:
Clean Structure:
API/
AppName.API/
Controllers/
Filters/
Core/
AppName.Application/
Contracts/
Persistence/ (this has the interfaces for the repository classes)
Features/
DTOs/
Services/
Validators/
AppName.Domain/
Entities/
Infrastructure/
AppName.Persistence/
Contexts/
Repositories/ (this has the implementations for the repository classes)
Clean Dependencies:
Hi , I am new to c# and I have a problem with running the code , everytime I click the green button that looks like this ▶️ a pop up appears with the title "attach to process" and a bunch of things ending in .exe , for example "AsusOSD.exe" , and the code doesn't run , what do I do?
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
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);
}
}
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.
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
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!
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.
Currently basing things off the IP the user last logged in from but users are complaining it is happening too often.
Create a HTTPs/SSL Web Server in C#.NET from Scratch: https://www.youtube.com/playlist?list=PL7JwiD5MYNPF_SzDrqOEfe77A3wD5sVfL
Lets learn something today 🥰. If you like it kindly support and give ur valuable feedbacks.
I am using below library to generate PDF report.
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?
There's an annoying Display box blocking my code
it says
// Tab to accept
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(); } } }
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?
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:
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!