Hot answers tagged

250

I disagree with It is hard to read in general especially to "in general". These language features may be hard to read for beginners when they see them the first time, but they were actually added to the language to make code more concise. So after one gets used to them (which should not last longer than using them half a dozen times) they should make ...


165

Instead of returning an int, return a value object that has the validation hard-coded. This is a case of primitive obsession and its fix. // should be class, not struct as struct can be created without calling a constructor public class ValidNumber { public int Number { get; } public ValidNumber(int number) { if (number <= 5) ...


113

Strangely, the history of C-style programming language doesn’t start with C. Dennis Ritchie explains well the challenges of C’s birth in this article. When reading it, it becomes obvious that C inherited a part of its language design from its predecessor BCPL, and especially the operators. The section “Neonatal C” of the aforementioned article explains how ...


92

Syntactic Sugar is Good™. What is a while loop if not sugar for goto? let me tell you what it is: easier to read and less error prone. Yes, you can do less with while than with goto and conditionals... that does not make it not sugar. It is sugar all the way down (I mean abstractions). We are getting to a point where we are closer to writing what we intend ...


51

I cannot think of a reason why the designers chose to deviate from the principle that single is bitwise and double is logical here, That's not the principle in the first place; once you realize that, it makes more sense. The better way to think of & vs && is not binary and Boolean. The better way is to think of them as eager and lazy. The &...


47

You have to expect your program to terminate for more reasons than just an unhandled exception anyway, like a power failure, or a different background process which crashes the whole system. Therefore I would recommend to terminate and restart the application, but with some measures to mitigate the consequences of such a restart and minimize the possible ...


47

The calling code which instantiated a FooRepository object is passing an IDbConnection object and therefore has the right to access this information later on This is not true when you're dealing with things like the factory pattern, where the instantiator of the object is not the handler of the object. Factory patterns quite often exist specifically because ...


44

There are various ways to call native code from c# P/Invoke - allows c-style method calls directly from c# code. If the API does not expose c-style (i.e. extern C) functions you will need a wrapper that does this. If the API uses any kind of objects this will probably be an painful approach. C++/CLI - This allows you to use .Net types in a c++ project. So ...


39

What you are looking for is a well-known approach called Design by Contract. It was supported directly in the framework in version 4.0. DISCLOSURE: Be careful when adding code contracts to a new project in 2019. Current status of further maintenance by Microsoft is not fully clear, see this SO post, maybe because of missing popularity. DBC allows to ...


35

Using many locks may cause some problems: The number locks a process may request is often limited by the OS. Your system may, indeed, run out of locks. Note: this depends on the kind of lock. The number of interprocess locks such as Mutex and all other synchronisation primitives derived from WaitHandle is limited by the OS. The Compare-And-Swap cache line ...


33

Well, first of all, let's tweak your interface a bit. public interface IComponent { void Enable(); void Disable(); bool IsEnabled { get; } } Now then. What could potentially go wrong here? For example, could an exception be thrown in the Enable() or Disable() methods? What state would IsEnabled be in then? Even if you use Code Contracts, I ...


32

You're asking too much of C# Interfaces. C# Interfaces are contracts. They say what pack of methods a given class implements, and they guarantee that those methods will be there if someone calls them. That said, that is also the only thing C# Interfaces do. They are completely oblivious to what the implemented methods do. They are free to do whatever they ...


30

Saying that it is an anti-pattern to make public methods virtual or abstract because of the developer of a derived class that implements Method1 and overrides Method2 has to repeat the argument validation is mixing up cause and effect. It makes the assumption that every overrideable method requires a non-customizable argument validation. But it is ...


30

It depends to some extent on the application you're developing but in general, I'd say that if your application encounters an unhandled exception, you need to terminate it. Why? Because you can no longer have any confidence in the state of the application. Definitely, provide a helpful message to the user, but you should ultimately terminate the ...


29

The problem The purpose of having these result classes derive from the same interface is so that the interface becomes what the consumer knows and works with. The consumer doesn't care about the specific implementing classes. However, your interface doesn't contain anything. You're using it as a marker interface. If I, as a consumer, receive an ...


27

This code is a generator (Microsoft documentation refer to these as Iterator Methods, see also yield (C# Reference)): public IEnumerable<string> GetHelloWorld() { yield return "Hello"; yield return "World"; } It is a method that generates an iterator enumerable. They are evaluated lazily, as you probably are aware. That is ...


25

To complement the other answers, I'd like to partially comment on the following note in the OP by providing a broader context: An interface seems like a good concept, if only I could also specify additional things or restrictions it's supposed to implement. You are making a good point here! Let us consider on which levels we can specify such restrictions ...


24

Although other answers implicitly touch upon this, the first thing to consider when asking "How readable is this code?" is, Who is the audience for this code? Here are several potential audiences for your code: Developers who are not C# programmers and do not intend to learn C#. For these people, write in a way that is common to many languages at least one ...


24

Create a new method with the additional parameter and move all the code from the original method in it, making it use the additional parameter the way you are supposed to. Leave the original method (without the additional parameter) which would just call the new method with some default value of the additional parameter, basically making it a wrapper method. ...


23

Dictionaries (C# or otherwise) are simply a container where you look up a value based on a key. In many languages it's more correctly identified as a Map with the most common implementation being a HashMap. The problem to consider is what happens when a key does not exist. Some languages behave by returning null or nil or some other equivalent value. ...


23

Some good answers here on the general principles of hashtables/dictionaries. But I thought I'd touch on your code example, int x; if (dict.TryGetValue("key", out x)) { DoSomethingWith(x); } As of C# 7 (which I think is around two years old), that can be simplified to: if (dict.TryGetValue("key", out var x)) { DoSomethingWith(x); } And of course ...


23

You're trying to design by contract, where that contract is that the return value must be greater than 5. Unfortunately, if you're relying on an interface, the only contract you have is the method signatures. I'd suggest using an abstract class instead. Here's an approach I would take in Java: public abstract class SomeAbstraction { public final int ...


22

TL;DR C inherited the ! and ~ operators from another language. Both && and || were added years later by a different person. Long Answer Historically, C developed out of the early languages B, which was based on BCPL, which was based on CPL, which was based on Algol. Algol, the great-granddaddy of C++, Java and C#, defined true and false in a way ...


21

State transitions can be represented by separate interfaces per state: public interface IEnabledComponent { IDisabledComponent ToDisabled(); } public interface IDisabledComponent { IEnabledComponent ToEnabled(); } This is much more powerful and safe, since you can expose different methods depending on the current state. In particular you wouldn't ...


19

If you're arriving at this a little late, like me, it turns out the .NET team addressed it through a bunch of parameter attributes like MaybeNullWhen(returnValue: true) in the System.Diagnostics.CodeAnalysis space which you can use for the try pattern. For example: how does generic code like Dictionary.TryGetValue deal with this? bool TryGetValue(TKey ...


19

Couple of pointers. You should never expose stacktrace to users. Thats a security risk. You should also never expose exception messages to users, only for custom exceptions that you know can not contain sensitive information is ok to expose. You should never build your release candidate on a developer machine. You should use a build agent for this. The ...


18

You've taken the line from MSDN out of context. The most important part of the page is the first sentence: "The in keyword causes arguments to be passed by reference." It is primarily in this respect that the keyword is similar to out and ref. This is important when you pass large structs to functions. Passing them without a keyword is inefficient because ...


17

There seem to be two main thrusts to your critique: Events are fragile in the face of hostile or buggy subscribers. The publish-subscribe metaphor doesn't match your intuition. Let's deal with the second point first. All metaphors in design patterns are analogies, not isomorphisms. The criticism is valid, but remember, the design was not motivated by a ...


16

Since the reference to the wrapped XElement is immutable, there is no externally observable difference between two instances of XmlWrapper that wrap the same element, so it makes sense to overload == to reflect this fact. Client code almost always cares about logical equality (which, by default, is implemented using reference equality for reference types). ...


16

C# enums are a set of named [integral numeric] constants. Each constant in the enum has a numeric value. So the word you are looking for, for the "the index integer of a enum", is just "value".


Only top voted, non community-wiki answers of a minimum length are eligible