Pull to refresh
107.9

C# *

Multi-paradigm programming language encompassing strong typing, imperative, declarative, functional, generic, object-oriented (class-based), and component-oriented programming disciplines

Show first
Rating limit
Level of difficulty

Announcing .NET Core 3.0 Preview 6

Reading time 8 min
Views 1.2K

Today, we are announcing .NET Core 3.0 Preview 6. It includes updates for compiling assemblies for improved startup, optimizing applications for size with linker and EventPipe improvements. We’ve also released new Docker images for Alpine on ARM64.



Read more →
Total votes 11: ↑9 and ↓2 +7
Comments 0

.NET: Tools for working with multi-threading and asynchrony – Part 1

Reading time 18 min
Views 19K
I have originally posted this article in CodingSight blog
The second part of the article is available here

The need to do things in an asynchronous way – that is, dividing big tasks between multiple working units – was present long before the appearance of computers. However, when they did appear, this need became even more obvious. It is now 2019, and I’m writing this article on a laptop powered by an 8-core Intel Core CPU which, in addition to this, is simultaneously working on hundreds of processes, with the number of threads being even larger. Next to me, there lies a slightly outdated smartphone which I bought a couple of years ago – and it also houses an 8-core processor. Specialized web resources contain a wide variety of articles praising this year’s flagship smartphones equipped with 16-core CPUs. For less then $20 per hour, MS Azure can give you access to a 128-core virtual machine with 2 TB RAM. But, unfortunately, you cannot get the most out of this power unless you know how to control interaction between threads.
Read more →
Total votes 8: ↑6 and ↓2 +4
Comments 4

Nullable Reference types in C# 8.0 and static analysis

Reading time 12 min
Views 3.6K

Picture 9


It's not a secret that Microsoft has been working on the 8-th version of C# language for quite a while. The new language version (C# 8.0) is already available in the recent release of Visual Studio 2019, but it's still in beta. This new version is going to have a few features implemented in a somewhat non-obvious, or rather unexpected, way. Nullable Reference types are one of them. This feature is announced as a means to fight Null Reference Exceptions (NRE).
Read more →
Total votes 19: ↑18 and ↓1 +17
Comments 1

The architecture of an exceptional situation: pt.2 of 4

Reading time 13 min
Views 1.3K

I guess one of the most important issues in this topic is building an exception handling architecture in your application. This is interesting for many reasons. And the main reason, I think, is an apparent simplicity, which you don’t always know what to do with. All the basic constructs such as IEnumerable, IDisposable, IObservable, etc. have this property and use it everywhere. On the one hand, their simplicity tempts to use these constructs in different situations. On the other hand, they are full of traps which you might not get out. It is possible that looking at the amount of information we will cover you’ve got a question: what is so special about exceptional situations?


However, to make conclusions about building the architecture of exception classes we should learn some details about their classification. Because before building a system of types that would be clear for the user of code, a programmer should determine when to choose the type of error and when to catch or skip exceptions. So, let’s classify the exceptional situations (not the types of exceptions) based on various features.

Read more →
Total votes 10: ↑9 and ↓1 +8
Comments 0

Let's help QueryProvider deal with interpolated strings

Reading time 5 min
Views 1.6K

Specifics of QueryProvider


QueryProvider can’t deal with this:


var result = _context.Humans
                      .Select(x => $"Name: {x.Name}  Age: {x.Age}")
                      .Where(x => x != "")
                      .ToList();

It can’t deal with any sentence using an interpolated string, but it’ll easily deal with this:


var result = _context.Humans
                      .Select(x => "Name " +  x.Name + " Age " + x.Age)
                      .Where(x => x != "")
                      .ToList();

The most painful thing is to fix bugs after turning on ClientEvaluation (exception for client-side calculation), since all Automapper profiles should be strictly analyzed for interpolation. Let’s find out what’s what and propose our solution to the problem.

Read more →
Total votes 12: ↑11 and ↓1 +10
Comments 0

Support of Visual Studio 2019 in PVS-Studio

Reading time 19 min
Views 1K


Support of Visual Studio 2019 in PVS-Studio affected a number of components: the plugin itself, the command-line analyzer, the cores of the C++ and C# analyzers, and a few utilities. In this article, I will briefly explain what problems we encountered when implementing support of the IDE and how we addressed them.
Read more →
Total votes 31: ↑30 and ↓1 +29
Comments 0

Exceptional situations: part 1 of 4

Reading time 11 min
Views 2.1K


Introduction


It’s time to talk about exceptions or, rather, exceptional situations. Before we start, let’s look at the definition. What is an exceptional situation?


This is a situation that makes the execution of current or subsequent code incorrect. I mean different from how it was designed or intended. Such a situation compromises the integrity of an application or its part, e.g. an object. It brings the application into an extraordinary or exceptional state.


But why do we need to define this terminology? Because it will keep us in some boundaries. If we don’t follow the terminology, we can get too far from a designed concept which may result in many ambiguous situations. Let’s see some practical examples:


 struct Number
 {
     public static Number Parse(string source)
     {
         // ...
         if(!parsed)
         {
             throw new ParsingException();
         }
         // ...
     }

     public static bool TryParse(string source, out Number result)
     {
        // ..
        return parsed;
     }
 }

This example seems a little strange, and it is for a reason. I made this code slightly artificial to show the importance of problems appearing in it. First, let’s look at the Parse method. Why should it throw an exception?

Read more →
Total votes 27: ↑26 and ↓1 +25
Comments 2

Should array length be stored into a local variable in C#?

Reading time 6 min
Views 17K
I notice that people often use construction like this:

var length = array.Length;
for (int i = 0; i < length; i++) {
    //do smth
}

They think that having a call to the Array.Length on each iteration will make CLR to take more time to execute the code. To avoid it they store the length value in a local variable.
Let’s find out (once and for all !) if this is a viable thing or using a temporary variable is a waste of time.
Read more →
Total votes 13: ↑13 and ↓0 +13
Comments 0

DynamicData: Dynamic Collections, the MVVM Architecture, and Reactive Extensions

Reading time 10 min
Views 17K


February 2019 marked the release of ReactiveUI 9 — the cross-platform framework for building GUI applications on the Microsoft .NET platform. ReactiveUI is a tool for tight integration of reactive extensions with the MVVM design pattern. You could familiarize yourself with the framework via a series of videos or the welcome page of the documentation. The ReactiveUI 9 update includes numerous fixes and improvements, but probably the most crucial and interesting one is integration with the DynamicData framework, allowing you to work with dynamic collections in Reactive fashion. Let’s find out what we can use DynamicData for and how this powerful reactive framework works under the hood!

Read more →
Total votes 14: ↑12 and ↓2 +10
Comments 2

Blazor now in official preview

Reading time 4 min
Views 2.2K

With this newest Blazor release we’re pleased to announce that Blazor is now in official preview! Blazor is no longer experimental and we are committing to ship it as a supported web UI framework including support for running client-side in the browser on WebAssembly.


A little over a year ago we started the Blazor experimental project with the goal of building a client web UI framework based on .NET and WebAssembly. At the time Blazor was little more than a prototype and there were lots of open questions about the viability of running .NET in the browser. Since then we’ve shipped nine experimental Blazor releases addressing a variety of concerns including component model, data binding, event handling, routing, layouts, app size, hosting models, debugging, and tooling. We’re now at the point where we think Blazor is ready to take its next step.


Blazor icon
Read more →
Total votes 10: ↑10 and ↓0 +10
Comments 0

Breaking down the fundamentals of C #: allocating memory for a reference type on the stack

Reading time 6 min
Views 6.9K
This article will show you the basics of types internals, as of course an example in which the memory for the reference type will be allocated completely on the stack (this is because I am a full-stack programmer).



Disclaimer


This article does not contain material that should be used in real projects. It is simply an extension of the boundaries in which a programming language is perceived.

Before proceeding with the story, I strongly recommend you to read the first post about StructLayout, because there is an example that will be used in this article (However, as always).
Read more →
Total votes 7: ↑6 and ↓1 +5
Comments 0

What happens behind the scenes C#: the basics of working with the stack

Reading time 6 min
Views 7.2K
I propose to look at the internals that are behind the simple lines of initializing of the objects, calling methods, and passing parameters. And, of course, we will use this information in practice — we will subtract the stack of the calling method.

Disclaimer


Before proceeding with the story, I strongly recommend you to read the first post about StructLayout, there is an example that will be used in this article.

All code behind the high-level one is presented for the debug mode, because it shows the conceptual basis. JIT optimization is a separate big topic that will not be covered here.

I would also like to warn that this article does not contain material that should be used in real projects.

First — theory


Any code eventually becomes a set of machine commands. Most understandable is their representation in the form of Assembly language instructions that directly correspond to one (or several) machine instructions.

Read more →
Total votes 11: ↑10 and ↓1 +9
Comments 0

Disposable pattern (Disposable Design Principle) pt.3

Reading time 15 min
Views 3.9K


Multithreading


Now let’s talk about thin ice. In the previous sections about IDisposable we touched one very important concept that underlies not only the design principles of Disposable types but any type in general. This is the object’s integrity concept. It means that at any given moment of time an object is in a strictly determined state and any action with this object turns its state into one of the variants that were pre-determined while designing a type of this object. In other words, no action with the object should turn it into an undefined state. This results in a problem with the types designed in the above examples. They are not thread-safe. There is a chance the public methods of these types will be called when the destruction of an object is in progress. Let’s solve this problem and decide whether we should solve it at all.


This chapter was translated from Russian jointly by author and by professional translators. You can help us with translation from Russian or English into any other language, primarily into Chinese or German.

Also, if you want thank us, the best way you can do that is to give us a star on github or to fork repository github/sidristij/dotnetbook.
Read more →
Total votes 12: ↑11 and ↓1 +10
Comments 0

How to push parameters into methods without parameters in safe code

Reading time 4 min
Views 6.5K
Hello. This time we continue to laugh at the normal method call. I propose to get acquainted with the method call with parameters without passing parameters. We will also try to convert the reference type to a number — its address, without using pointers and unsafe code.

Read more →
Total votes 14: ↑13 and ↓1 +12
Comments 0

Memory and Span pt.3

Reading time 10 min
Views 2.5K


Memory<T> and ReadOnlyMemory<T>


There are two visual differences between Memory<T> and Span<T>. The first one is that Memory<T> type doesn’t contain ref modifier in the header of the type. In other words, the Memory<T> type can be allocated both on the stack while being either a local variable, or a method parameter, or its returned value and on the heap, referencing some data in memory from there. However, this small difference creates a huge distinction in the behavior and capabilities of Memory<T> compared to Span<T>. Unlike Span<T> that is an instrument for some methods to use some data buffer, the Memory<T> type is designed to store information about the buffer, but not to handle it. Thus, there is the difference in API.


  • Memory<T> doesn’t have methods to access the data that it is responsible for. Instead, it has the Span property and the Slice method that return an instance of the Span type.
  • Additionally, Memory<T> contains the Pin() method used for scenarios when a stored buffer data should be passed to unsafe code. If this method is called when memory is allocated in .NET, the buffer will be pinned and will not move when GC is active. This method will return an instance of the MemoryHandle structure, which encapsulates GCHandle to indicate a segment of a lifetime and to pin array buffer in memory.

This chapter was translated from Russian jointly by author and by professional translators. You can help us with translation from Russian or English into any other language, primarily into Chinese or German.

Also, if you want thank us, the best way you can do that is to give us a star on github or to fork repository github/sidristij/dotnetbook.
Read more →
Total votes 9: ↑9 and ↓0 +9
Comments 0

Memory and Span pt.2

Reading time 9 min
Views 3.2K


Span<T> usage examples


A human by nature cannot fully understand the purpose of a certain instrument until he or she gets some experience. So, let’s turn to some examples.


ValueStringBuilder


One of the most interesting examples in respect to algorithms is the ValueStringBuilder type. However, it is buried deep inside mscorlib and marked with the internal modifier as many other very interesting data types. This means we would not find this remarkable instrument for optimization if we haven’t researched the mscorlib source code.


What is the main disadvantage of the StringBuilder system type? Its main drawback is the type and its basis — it is a reference type and is based on char[], i.e. a character array. At least, this means two things: we use the heap (though not much) anyway and increase the chances to miss the CPU cash.


Another issue with StringBuilder that I faced is the construction of small strings, that is when the resulting string must be short e.g. less than 100 characters. Short formatting raises issues on performance.


This chapter was translated from Russian jointly by author and by professional translators. You can help us with translation from Russian or English into any other language, primarily into Chinese or German.

Also, if you want thank us, the best way you can do that is to give us a star on github or to fork repository github/sidristij/dotnetbook.
Read more →
Total votes 12: ↑11 and ↓1 +10
Comments 0

Checking the Roslyn Source Code

Reading time 21 min
Views 1.6K
PVS-Studio vs Roslyn

Once in a while we go back to the projects that we have previously checked using PVS-Studio, which results in their descriptions in various articles. Two reasons make these comebacks exciting for us. Firstly, the opportunity to assess the progress of our analyzer. Secondly, monitoring the feedback of the project's authors to our article and the report of errors, which we usually provide them with. Of course, errors can be corrected without our participation. However, it is always nice when our efforts help to make a project better. Roslyn was no exception. The previous article about this project check dates back to December 23, 2015. It's quite a long time, in the view of the progress that our analyzer has made since that time. Since the C# core of the PVS-Studio analyzer is based on Roslyn, it gives us additional interest in this project. As a result, we're as keen as mustard about the code quality of this project. Now let's test it once again and find out some new and interesting issues (but let's hope that nothing significant) that PVS-Studio will be able to find.
Read more →
Total votes 34: ↑34 and ↓0 +34
Comments 0

Authors' contribution