Questions tagged [c#]
C# is a multiparadigm, managed, garbage-collected object-oriented programming language created by Microsoft in parallel with the .NET platform
4,975 questions
4
votes
1
answer
104
views
Async-ifying WPF Window.Show()?
I'm working on a WPF application which has many user interactions which start with opening a non model window, allowing some interaction with the window and the rest of the application (think ...
2
votes
2
answers
302
views
How should multiple ViewModels communicate in a larger WPF MVVM application?
I’m working on a WPF MVVM application that has grown beyond just one or two User Controls. I now have multiple ViewModels that need to react to each other’s actions (e.g., selecting a customer in one ...
8
votes
4
answers
2k
views
Entity Framework - Is there a safety mechanism to prevent accidentally running Update-Database?
When using Entity Framework and running the Update-Database command, non-updated applications that rely on the database crash due to database context changes.
Usually teams have a production database ...
4
votes
1
answer
1k
views
CA-1822: Mark members as static Roslyn recommendation will not unnecessarily increase memory consumption?
My job uses SonarQube as part of the CI/CD quality gate. One of the "Maintainability" issues (severity: medium) raised is the CA-1822: Mark members as static.
The link explains the added ...
1
vote
3
answers
244
views
Should HTTP clients be encapsulated in a C#/.NET library?
I have a C# library that contains all the logic to send requests to a remote endpoint, including marshalling/unmarshalling and encrypting/decrypting requests and responses. It contains an HttpClient ...
0
votes
2
answers
149
views
What are the trade-offs of recursively invoking an extension method as extension vs static?
When using recursion in an extension method, there are two different ways to invoke the method from within itself.
Option 1: As an extension method
internal static class MyExtension
{
public ...
16
votes
10
answers
5k
views
C#'s Aversion to Array
I have noticed in documentation, looking at open-source code bases, and just a general sense in the industry that C# developers largely prefer to use List<> or IEnumerable<> over simple ...
2
votes
3
answers
170
views
Should a web framework / template like Admin-LTE be put in source control alongside our own code?
My team does predominantly back-end work in C#, with a smattering of front-end web development using Angular. We're starting a new website project, based on the Admin LTE framework / template. This is ...
0
votes
2
answers
338
views
C# - Entity handler correct use clean code
I have a question about setting up my service. My main concern is if the design is clean and in order. Whether it meets the SOLID principles and does not spill out on me.
I have entities like order ...
3
votes
1
answer
162
views
Approaches to Razor without combining C# in HTML
The move to MVC and MVVM has not been easy for me. Combining multiple languages in single pages with inline code is something I find disorienting. I'd like to remedy this by attempting to use Razor ...
2
votes
1
answer
179
views
Should I split endpoints by parameter requirements?
Preface: This will not be available publicly or to third parties, so I am not concerned about users having the background knowledge to properly form GET requests. These are also not only analytical ...
1
vote
1
answer
320
views
Is there a better way to soft delete navigation properties in Entity Framework 6 when using Repository pattern?
public void ReassignLineItems(InvoiceUpdateDto invoiceUpdate)
{
Invoice invoiceInRepository = _unitOfWork.InvoiceRepository
.FirstOrDefault(invoice => invoice.Id == invoiceUpdate.Id);
...
2
votes
1
answer
144
views
Using partials to automate form inputs creation
My main focus is having as little duplicate code/files as possible.
Most of the HTML I write is almost identical.
There is already a form template which holds the form and several necessities. That ...
1
vote
1
answer
175
views
ASP.NET MVC and Web API Together vs. ASP.NET MVC with JSON-Returning Action Methods
In an ASP.NET MVC application with views that make AJAX calls for widgets like dropdowns and data grids, is it better to use Web API controllers or regular MVC action methods that return JSON?
The ...
0
votes
2
answers
237
views
Testing C# app backed by MSSQL database and Entity Framework - seeking advices for going with "test double" approach
I am new to C#, and Windows (coming from Python, Linux background). I need to add tests
to an existing C# codebase, which relies on a MSSQL database and Entity Framework.
In my old days when testing ...
1
vote
3
answers
516
views
C# var vs. interface vs. concrete class in object instantiation
As we know, there are (at least) four ways to instantiate a class object in C#. But I've never quite understood why some ways are better than others.
First of all, you can explicitly declare the ...
1
vote
3
answers
190
views
Are there non-inheritance-chain-mess ways to make modular libraries that rely on Entity Framework based on one DB context in the using project?
I am developing some modular libraries that contain common APIs, data, and functionality. One of the core assumptions to these libraries is you would use which you want to compose your project, but ...
4
votes
4
answers
473
views
Primary constructors for depedency injection
Microsoft identifies dependency injection as one of the uses for primary constructors.
public class ExampleController(IService service) : ControllerBase
{
[HttpGet]
public ActionResult<...
0
votes
4
answers
282
views
Use-cases for Expression<TDelegate> except translating to another language?
So I just learned about Expression<TDelegate>. As a library author this really intrigued me; my libraries make extensive use of source generators to generate both high-performance code and code ...
1
vote
1
answer
179
views
NUnit testOf attribute usage
What are the use cases of TestOf? I'm new to NUnit testing and from what I have seen, most people don't use this attribute that much.
From my experience, TestOf helped me to quickly identify what ...
17
votes
5
answers
3k
views
Should parameter names describe their object type?
I'm unsure whether parameter names should describe their object types or if shorter, more concise names are preferable.
Consider the following two method signatures:
public void PrintPoint(...
3
votes
3
answers
979
views
Testing for non-existence of a method in API
I am designing a fluent builder pattern API that branches and allows different options based on what has already been called.
For example: Build().Foo().Bar() is valid code, but Build().Baz().Bar() ...
5
votes
5
answers
2k
views
Is it ok to make a wrapper method just for readability? And is this example more readable with a wrapper method?
In one of the flows we have too many returns that look like this:
PaymentResponse<ProviderReservedAccountsResponse>.Failed(
new Error(
ErrorCode.ReservedAccountsCreationInProgress....
3
votes
1
answer
440
views
Clean Architecture using interfaces or Mediator approach?
I'm starting a new project and I want to follow a Clean Architecture(ish) approach.
I've modeled my projects in that manner (attached diagram).
For the API I'm using FastEndpoint since I like it, it'...
2
votes
2
answers
528
views
Advanced Scenarios in Clean Architecture
We have a very complex and mature ASP.NET web application that is about 20 years old and has 5 million lines of code spread across roughly 30 project in a single monolithic solution.
It's running on ....
-2
votes
1
answer
216
views
Best Practices for Managing Multiple Entity Types in ASP.NET Core
I'm working on an ASP.NET Core application that requires handling multiple types of a single entity. Each type has its own properties and validation rules, which has led to confusion and complexity in ...
0
votes
1
answer
260
views
Best approach to map user roles dynamically in ASP.NET Core Identity register method?
I'm working on an ASP.NET Core application that uses Identity for user management. I have an AccountService with a Register function, where I accept a RegisterBaseDto that contains the role ...
3
votes
5
answers
2k
views
C# List vs Dictionary cost vs benefit with complex keys
I am designing a program and I am looking to decide over a Dictionary vs a List.
Since I know I have unique values per item I imagined a Dictionary/List that looks like:
Dictionary<(int k1, string ...
0
votes
3
answers
309
views
Design and communication between microservies
To learn about things like microservices, messaging brokers and all other new and fancy things, I decided to create microservices that will let me monitor my base within Minecraft (done via ...
1
vote
3
answers
620
views
Autogenerate DTO classes?
Yesterday I screwed up:
One of the classes of my C# contained a property, called "DeliverdQuantity" (yep, there's a spelling mistake indeed). When I saw that, I decided to correct that, ...
0
votes
2
answers
128
views
Modeling value object when fields' existence depends on state of other fields
I am practicing tactical DDD and having trouble as exemplified below. Fundamentally, whether some fields of the value object should be nullable depends on another field of the same value object. ...
4
votes
3
answers
2k
views
Not await an asynchronous method because it is like an endless loop - good practice?
I inherited a piece of software. This program is connected to an external hardware, which is a measurement device. Every 100 milliseconds, a value is read from this device and displayed to the user. ...
0
votes
2
answers
1k
views
C# readability - async/await or return for wrapping asynchronous functions?
Say I have an asynchronous method:
public async Task DoThing(int x)
{
// ...
}
Now, I want to wrap this method with a new method. Each of these two options are functionally equivalent:
public ...
1
vote
2
answers
875
views
Best practice for using models between layers in mvc
I'm working on an MVC application using C#/asp. The project is following an n-tier architecture style with a separate data layer, domain layer and presentation layer. My question is related to the use ...
-2
votes
1
answer
330
views
What is a component in C#?
Introduction
Components are an important building block of software. In terms of software architecture, there are a lot of principles regarding components that should be adhered to (high cohesion, low ...
5
votes
7
answers
586
views
Exceptions and the Liskov Substitution Principle
Consider the following scenario.
I have an interface IService:
public interface IService
{
void DoSomething();
}
with an implementation:
public class Implementation : IService
{
// This might ...
13
votes
4
answers
3k
views
How to name uppercase variables when using the camelCase convention?
I am writing a C# class and one of the fields is an API endpoint. Being that API is an acronym and is written in all uppercase letters, what is the correct way to name the field _APIEndpoint, ...
0
votes
3
answers
447
views
Adding a CLI to a Windows service
I have a Windows service that I would like to extend and add a CLI to it similar to docker or Elastic Agent, so I have a question about what kind of approach I should use for the *.exe to communicate ...
3
votes
1
answer
455
views
Gradual upgrade of an inherited .NET Framework project
I'm seeking advice on the best approach to upgrade a legacy .NET Framework project to a newer version. The project currently consists of over 80 projects, and a complete rewrite would be a time-...
1
vote
0
answers
87
views
When taking sections of an existing c# codebase to create a module/package of code for general use, how should we configure the module?
When spinning off sections of a (C#) codebase to create libraries/package for use by other users within a team/organization, what are important considerations in terms of code & package ...
0
votes
1
answer
317
views
Is IRepository allowed to know about database entities?
I am trying to apply Robert Martin's Clean Architecture on my .NET project. In one of chapters about boundary, it talks about that database interface should reside in business logic component rather ...
3
votes
3
answers
317
views
Handle hierarchical relationships between large number of enums
I am working on a C# project and I have a somewhat large number of labels (~100) that have some sort of relationships between one another. Here is a minimal dummy example that illustrates this:
...
0
votes
2
answers
152
views
Resolving dependencies independently of the IoC container
I'm working on a component, let's call it MyComponent, which is intended to be used by various applications. These applications will get MyComponent as a NuGet package for instance.
Assume that ...
0
votes
1
answer
100
views
.NET - Communication between services and Power BI
I have the following problem which I don't know much about. I have a ServiceA that returns customer data on transactions and a ServiceB that has reports, also my environment uses Power BI from ...
0
votes
2
answers
2k
views
Setting up private properties for unit testing
I'm doing some TDD practice for my own learning.
I'm trying to figure out how to transparently set up private properties of an object to support testing.
I have a binary tree node:
internal class Node ...
0
votes
0
answers
135
views
Multi-tenant (realm based) REST Web API authentication
We're building a multi-tenant setup with a C# Web API and KeyCloak for auth and APISIX as application gateway. APISIX handles the authentication and passes an X-Access-Token to our API when ...
0
votes
3
answers
325
views
Use of environment variable or appsettings as a counter, good or bad practice [closed]
I'm wondering if it's bad practice to have a variable in a webserver which counts the amount of incoming requests and put it in an environment variable.
In C# for example you have System.Configuration....
2
votes
4
answers
920
views
OneOf with multiple steps and early returns
Looking for the best way to use OneOf multiple times, returning early depending on the result, specifically if you can get an Error along the way.
For example, consider a builder where you need to ...
3
votes
2
answers
418
views
Invariant rule in Liskov Substitution Principle
From Liskov Substitution Principle, I am still not very clear about the invariant rule. I read through many posts but I still have doubts.
My example is picked from this blog, the example is slightly ...
5
votes
1
answer
876
views
Does C# 8 reference type nullability make Option/Result monad obsolete?
As the most common exceptions in my project are NullReferenceExceptions I'm trying to find a way to limit the occurrence of problems with unexpected or unhandled nulls to the minimum.
One of the ...