Questions tagged [c#]
C# is a multiparadigm, managed, garbage-collected object-oriented programming language created by Microsoft in parallel with the .NET platform
406
questions
50
votes
2
answers
24k
views
Choosing the right Design Pattern
I've always recognized the importance of utilizing design patterns. I'm curious as to how other developers go about choosing the most appropriate one. Do you use a series of characteristics (like a ...
71
votes
8
answers
22k
views
How do you encode Algebraic Data Types in a C#- or Java-like language?
There are some problems which are easily solved by Algebraic Data Types, for example a List type can be very succinctly expressed as:
data ConsList a = Empty | ConsCell a (ConsList a)
consmap f ...
96
votes
8
answers
53k
views
Return magic value, throw exception or return false on failure?
I sometimes end up having to write a method or property for a class library for which it is not exceptional to have no real answer, but a failure. Something cannot be determined, is not available, not ...
5
votes
1
answer
2k
views
Derive from a base class but not include a condition in the base class's method
The current code looks like this:
public class Details
{
Public void Populate()
{
WriteChapterDetails();
}
public void WriteChapterDetails()
{
if ( ...
69
votes
12
answers
45k
views
Is catching general exceptions really a bad thing?
I typically agree with most code analysis warnings, and I try to adhere to them. However, I'm having a harder time with this one:
CA1031: Do not catch general exception types
I understand the ...
93
votes
11
answers
85k
views
Is static universally "evil" for unit testing and if so why does Resharper recommend it? [closed]
I have found that there are only 3 ways to unit test (mock/stub) dependencies that are static in C#.NET:
Moles
TypeMock
JustMock
Given that two of these are not free and one has not hit release 1.0, ...
72
votes
7
answers
81k
views
When to use abstract classes instead of interfaces with extension methods in C#?
"Abstract class" and "interface" are similar concepts, with interface being the more abstract of the two. One differentiating factor is that abstract classes provide method implementations for derived ...
251
votes
11
answers
29k
views
Why do many exception messages not contain useful details?
It seems there is a certain amount of agreement that exception messages should contain useful details.
Why is it that many common exceptions from system components do not contain useful details?
A few ...
306
votes
19
answers
157k
views
Are #regions an antipattern or code smell?
C# allows the use of #region/#endregion keywords to make areas of code collapsible in the editor. Whenever I do this though I do it to hide large chunks of code that could probably be refactored into ...
29
votes
5
answers
15k
views
Would you rather make private stuff internal/public for tests, or use some kind of hack like PrivateObject?
I am quite a beginner in code testing, and was an assert whore before. One thing worrying me in unit testing is that is often requires you to make public (or at least internal) fields that would have ...
88
votes
11
answers
12k
views
Did the developers of Java consciously abandon RAII?
As a long-time C# programmer, I have recently come to learn more about the advantages of Resource Acquisition Is Initialization (RAII). In particular, I have discovered that the C# idiom:
using (var ...
35
votes
6
answers
28k
views
Explicitly defining variable data types vs. using the keyword 'var'? [closed]
In C#, am I encouraged to use the all-purpose var keyword for every variable declaration? If yes, do I have to mention those special characters for literal values within the variable declaration like ...
22
votes
1
answer
2k
views
Unit testing for a scientific computing library
I've had a bit of experience with unit testing before, in what I call (not pejoratively) the classic software engineering project: an MVC, with a user GUI, a database, business logic in the middle ...
18
votes
3
answers
8k
views
Should Entity Framework 6 not be used with repository pattern?
So I am asking this after reading the following: Why shouldn't I use the repository pattern with Entity Framework?.
It seems there is a large split of people who say yay and those that say nay. ...
9
votes
2
answers
4k
views
Zero argument constructors and Always Valid entities
I have done a lot of reading recently about Always Valid domain entities. I have come to believe that in order to ensure the entities are always valid I need to:
1) Remove primitive obsession and ...
88
votes
11
answers
17k
views
Is it a bad practice to modify code strictly for testing purposes
I have a debate with a programmer colleague about whether it is a good or bad practice to modify a working piece of code only to make it testable (via unit tests for example).
My opinion is that it ...
63
votes
10
answers
12k
views
Readability versus maintainability, special case of writing nested function calls
My coding style for nested function calls is the following:
var result_h1 = H1(b1);
var result_h2 = H2(b2);
var result_g1 = G1(result_h1, result_h2);
var result_g2 = G2(c1);
var a = F(result_g1, ...
63
votes
17
answers
36k
views
Why use an OO approach instead of a giant "switch" statement?
I am working in a .Net, C# shop and I have a coworker that keeps insisting that we should use giant Switch statements in our code with lots of "Cases" rather than more object oriented approaches. His ...
36
votes
2
answers
37k
views
Separating data access in ASP.NET MVC
I want to make sure I'm following industry standards and best practices with my first real crack at MVC. In this case, it's ASP.NET MVC, using C#.
I will be using Entity Framework 4.1 for my model, ...
13
votes
4
answers
3k
views
Is the usage of internal scope blocks within a function bad style?
There are some (quite rare) cases where there is a risk of:
reusing a variable which is not intended to be reused (see example 1),
or using a variable instead of another, semantically close (see ...
57
votes
8
answers
9k
views
Why a static main method in Java and C#, rather than a constructor?
I’m Looking for a definitive answer from a primary or secondary source for why (notably) Java and C# decided to have a static method as their entry point, rather than representing an application ...
33
votes
6
answers
5k
views
I'd like to write an "ultimate shuffle" algorithm to sort my mp3 collection
I'm looking for pseudocode suggestions for sorting my mp3 files in a way that avoids title and artist repetition. I listen to crooners - Frank Sinatra, Tony Bennett, Ella Fitzgerald etc. singing old ...
140
votes
4
answers
193k
views
Creating database connections - Do it once or for each query?
At the moment I create a database connection when my web page is first loaded. I then process the page and run any queries against that conection. Is this the best way to do it or should I be creating ...
104
votes
14
answers
13k
views
At what point is brevity no longer a virtue?
A recent bug fix required me to go over code written by other team members, where I found this (it's C#):
return (decimal)CostIn > 0 && CostOut > 0 ? (((decimal)CostOut - (decimal)...
85
votes
10
answers
16k
views
Exceptions, error codes and discriminated unions
I've recently started a C# programming job, but I've got quite a bit of background in Haskell.
But I understand C# is an object-orientated language, I don't want to force a round peg into a square ...
56
votes
3
answers
70k
views
Which is a better practice - helper methods as instance or static?
This question is subjective but I was just curious how most programmers approach this. The sample below is in pseudo-C# but this should apply to Java, C++, and other OOP languages as well.
Anyway, ...
43
votes
3
answers
62k
views
What is message passing in OO?
I've been studying OO programming, primarily in C++, C# and Java. I thought I had a good grasp on it with my understanding of encapsulation, inheritance and polymorphism.
One frequently referenced ...
31
votes
3
answers
29k
views
Is it bad practice to use public fields? [duplicate]
Possible Duplicate:
When are Getters and Setters Justified
Why are public and private accessors considered good practice?
In my time as developer I learned that properties can be very useful. I ...
29
votes
9
answers
11k
views
When is primitive obsession not a code smell?
I have read plenty of articles recently that describe primitive obsession as a code smell.
There are two benefits of avoiding primitive obsession:
It makes the domain model more explicit. For ...
158
votes
8
answers
179k
views
How do you organize your projects? [closed]
Do you have any particular style of organizing projects?
For example, currently I'm creating a project for a couple of schools here in Bolivia, this is how I organized it:
TutoMentor (Solution)
...
92
votes
5
answers
127k
views
for vs. foreach vs. LINQ
When I write code in Visual Studio, ReSharper (God bless it!) often suggests me to change my old-school for loop in the more compact foreach form.
And often, when I accept this change, ReSharper goes ...
73
votes
8
answers
25k
views
Single Responsibility Principle - How Can I Avoid Code Fragmentation?
I'm working on a team where the team leader is a virulent advocate of SOLID development principles. However, he lacks a lot of experience in getting complex software out of the door.
We have a ...
19
votes
11
answers
57k
views
Recommended .NET / C# coding standards? [closed]
What coding standards do you think are important for .NET / C# projects? This could be anything from dealing with curly braces and spacing and pedantry like that. Or it could be more fundamental ...
16
votes
3
answers
16k
views
What is the benefit to having pure POCO models?
What is the major benefit of having pure POCO models? I get that Models should be clean and simple, but I tend to like to keep the maintenance of child objects within the model classes. For example ...
12
votes
9
answers
4k
views
How can designing for inheritance cause extra cost? [closed]
So I wanted to inherit from a sealed class in csharp and got burned. There is just no way to unseal it unless you have access to the source.
Then it got me thinking "why sealed even exists?". 4 ...
11
votes
3
answers
31k
views
Repository Pattern and Joined Queries
In conjunction with Unit Tests and Dependency Injection I (and my primary coworker) are exploring Repositories. However we cannot come to a solid plan of action for implementation.
In a basic ...
8
votes
3
answers
7k
views
What is the "best" way to approach validation from the perspective of a DDD purist?
I recently asked this question.
I am trying to decide where to put the validation in a DDD app. I believe it should be done at every layer.
I am now concentrating on the Domain model. I was ...
7
votes
2
answers
7k
views
Object Initializer in C# problem with readability
I wonder if object initializing have some performance gain in ASP.NET website. I have an office mate that told me that object initialization is much readable and faster than constructor. But one of my ...
3
votes
5
answers
9k
views
MVC4 : How to create model at run time?
In my project I am dynamically creating table by giving table name (ex. student) and adding fields to that table and then save table. Now, my table is created in SQL Server database.
Assume table ...
128
votes
10
answers
109k
views
Don't Use "Static" in C#?
I submitted an application I wrote to some other architects for code review. One of them almost immediately wrote me back and said "Don't use static. You can't write automated tests with static ...
82
votes
6
answers
19k
views
When to go Fluent in C#?
In many respects I really like the idea of Fluent interfaces, but with all of the modern features of C# (initializers, lambdas, named parameters) I find myself thinking, "is it worth it?", and "Is ...
47
votes
5
answers
34k
views
async+await == sync?
Stumbled upon this post that talks about making async web requests.
Now simplicity aside, if in real world, all you do is make an async request and wait for it in the very next line, isn't that the ...
46
votes
6
answers
75k
views
What is the best way to initialize a child's reference to its parent?
I'm developing an object model that has lots of different parent/child classes. Each child object has a reference to its parent object. I can think of (and have tried) several ways to initialize the ...
46
votes
11
answers
393k
views
For what reasons should I choose C# over Java and C++? [closed]
C# seems to be popular these days. I heard that syntactically it is almost the same as Java. Java and C++ have existed for a longer time. For what reasons should I choose C# over Java and C++?
42
votes
8
answers
44k
views
Private variable vs property?
When setting a value to a variable inside of a class most of the time we are presented with two options:
private string myValue;
public string MyValue
{
get { return myValue; }
set { myValue = ...
41
votes
11
answers
4k
views
Should a developer always use version control [duplicate]
Possible Duplicate:
Version control for independent developers?
I've heard statements to the effect of: "Well it's just me working on this project so I don't need to put it under source control" ...
40
votes
9
answers
48k
views
Constructor parameter validation in C# - Best practices
What is the best practice for constructor parameter validation?
Suppose a simple bit of C#:
public class MyClass
{
public MyClass(string text)
{
if (String.IsNullOrEmpty(text))
...
38
votes
6
answers
30k
views
Try/Catch/Log/Rethrow - Is Anti Pattern?
I can see several post where importance of handling exception at central location or at process boundary been emphasized as a good practice rather than littering every code block around try/catch. I ...
31
votes
4
answers
4k
views
Why do we need the async keyword?
I just started playing around with async/await in .Net 4.5. One thing I'm initially curious about, why is the async keyword necessary? The explanation I read was that it is a marker so the compiler ...
30
votes
5
answers
37k
views
When and why you should use void (instead of e.g. bool/int)
I occasionally run into methods where a developer chose to return something which isn't critical to the function. I mean, when looking at the code, it apparently works just as nice as a void and after ...