Aujourd'hui, j'ai reçu une excellente nouvelle : je viens d'avoir un deuxième sponsor dans les sponsors github. Cela signifie beaucoup pour moi ; plus que le $ (qui est toujours le bienvenu), cela signifie que le projet est d'une manière ou d'une autre utile à certaines personnes et que certaines d'entre elles peuvent se permettre de le reconnaître par le parrainage.
Je ne peux que vous dire un grand merci :), votre parrainage est apprécié.
Cela dit, j'aimerais souligner qu'il existe plusieurs façons de contribuer à des projets open source si vous le souhaitez ; certains impliquent de donner de l'argent, d'autres impliquent de donner du temps pour signaler des bogues, s'engager dans des discussions, contribuer avec des demandes d'extraction, proposer des modifications, etc.
Plus précisément dans le cas de Cecilifier, si vous souhaitez contribuer avec du code, nous pouvons organiser des séances en binôme pour aider à abaisser la barrière d'entrée et donner un aperçu de haut niveau ainsi que plonger dans certaines parties du code.
Si cela vous intéresse, laissez-moi simplement un commentaire dans ce post ou envoyez-moi un message privé sur Twitter / Mastodon (Je peux communiquer nativement en portugais, avec compétence en anglais et dans une certaine mesure en français - cette post c'est traduit de la version anglaise :) et nous pourrons arranger ça.
Sep 10, 2023
Sponsors, Sponsors, Sponsors (Francais)
Sponsors, Sponsors, Sponsors!
Today I've been grated with some great news: I've just got a second sponsor in github sponsors. This means a lot to me; more than the $ (which is always welcome), this means the project is somehow useful to some people and that some of those people can afford recognizing it by sponsorship.
I can only say thank you very much :), your sponsorship is appreciated.
That said, I'd like to emphasize that there are multiple ways to contribute to open source projects if you are willing to; some involve donating $, some involve donating time to file bugs, engaging in discussions, contributing with pull requests, proposing changes, etc.
Specifically in the case of Cecilifier, if you are interested in contributing with code we can arrange some pair sessions to help lowering the entry barrier and give some high level overview as well dive in some parts of the code.
If that interests you, just drop me a comment in this post or DM me in twitter / mastodon (I can communicate natively in Portuguese, proficiently in English and to some extent in French :) and we can arrange something.
Patriocinadores, Patriocinadores, Patriocinadores!
Hoje recebi uma ótima notícia: acabei de conseguir um segundo patrocinador no github. Isto significa muito para mim; mais do que o $ (que é sempre bem-vinda), isso significa que o projeto é, de alguma forma, útil para algumas pessoas e que algumas dessas pessoas podem se dar ao luxo de reconhecê-lo por meio de patrocínio.
Só posso dizer muito obrigado :), Seu patrocínio é muito apreciado.
Dito isto, gostaria de enfatizar que existem diversas maneiras de contribuir com projetos de código aberto se você estiver disposto a fazê-lo; alguns envolvem doar $, alguns envolvem doar tempo para registrar bugs, participar de discussões, contribuir com pull requests, propor mudanças, etc.
Especificamente no caso do Cecilifier, se você estiver interessado em contribuir com código, podemos organizar algumas sessões de pair programming para ajudar a diminuir a barreira de entrada e fornecer uma visão geral, bem como mergulhar em algumas partes do código.
Se isso lhe interessa, entre em contato comentando neste post ou me envie uma DM no twitter / mastodon (posso me comunicar nativamente em português, proficientemente em inglês e até certo ponto em francês :) e podemos combinar algo.
Aug 31, 2023
Structs em C# - diversão garantida - Parte 3/9: Inicialização de campos em structs
- Structs em C# - diversão garantida
- Rápida introdução à Value Types vs Reference Types.
- Inicialização de campos em estruturas (este post).
- Comportamento de construtores em estruturas.
- Outros cenários em que o comportamento de construtores em estruturas podem te surpreender.
- Argumentos default em construtores de estruturas (você ainda não esta confuso ?).
- Modificador `required` do C# 11 não vai salvar seu
c*trabalho. - Estruturas usadas como valor default de argumentos.
- Bonus: Evolução das estruturas em C#.
Continuando com nossa série sobre Value Types, dado o código abaixo, o que você espera que ele imprima (recomendo tentar responder antes de executá-lo):
Se você respondeu 0 (zero), acertou em cheio e provavelmente já possui um bom entendimento de como .NET/C# lida com instanciação/inicialização de campos de value types.; por outro lado, se você respondeu 32 provavelmente você foi levado ao engano.
Neste post discutirei brevemente um dos aspectos responsáveis por esse comportamento: inicialização de campos em .NET, ou para ser mais preciso, em C#.
De uma forma simplificada, sempre que o compilador C# encontra a inicialização de um campo o mesmo simplesmente move o código de inicialização para os construtores, ou seja, inicializar um campo é equivalente a definir seu valor nos construtores (campos estáticos são inicializados em construtores estáticos), portanto, dado o código abaixo:
o compilador C# irá processá-lo como se o mesmo fosse escrito como:
o
que pode ser confirmado no código IL gerado abaixo contudo, caso não esteja familiarizado com código IL, tenha o seguinte em mente:
- Não se deixe assustar com sua aparente complexidade.
- Incluí comentários para enfatizar as partes principais.
- Detalhes menos imporatntes foram omitidos.
- Não é necessário compreender todos os detalhes para entender o conceito principal.
As linhas 6~22 e 25~36 definem, respectivamente, um construtor sem parâmetros e um que recebe um número inteiro; observe que o código relacionado à inicialização do campo (`f = 42`) foi introduzido em ambos (linhas 9~11 e 29~31).
No próximo post começaremos a explorar o comportamento de construtores em estruturas (struct), também conhecido como a segunda parte do quebra-cabeça que explica por que o programa no topo do post imprime 0.
Como sempre, todo feedback é bem vindo.
Divirta-se!
Structs in C# are fun - Part 3/9: Field initialization in structs
- Structs in C# are fun.
- Brief introduction to Value Types vs Reference Types.
- Field initialization in structs (this post).
- Constructors and struct behavior.
- Other scenarios in which struct constructors behavior may surprise you.
- Struct with default argument values in constructors, a.k.a, are you not confused yet?
- `required` feature from C# 11 will not save your
a**job. - Struct used as default argument values.
- Bonus: Struct evolution in C#.
Continuing with our series on Value Types, given the code below, what do you expect it to print (I recommend trying to answer without running it first):
If you answered 0 (zero) you nailed it and probably already have a good understanding of how .NET/C# handles value type instantiation / field initialization; by the other hand, if you answered 32 you may have been tricked.
In this post I'll briefly discuss one of the aspects that leads to this behavior: field initialization in .NET, or to be more precise, in C#.
the C# compiler will process it as it was written as:
which you can confirm in the generated IL below, but keep the following in mind if you're not familiar with IL code:
- There's no need to be daunted by its apparent complexity.
- I've included comments to emphasize the key parts.
- I've omitted certain less crucial specifics.
- Grasping all the details isn't important to understand the main concept.
Lines 6~22 and 25~36 defines, respectively, the constructor taking no parameters and the one taking an integer; note that the code related to field initialization (`f = 42`) has been introduced in both (lines 9~11 and 29~31).
In the next post we'll start exploring struct constructor behavior, a.k.a, the second part of the puzzle that explains why the program at the top of the post prints 0.
As always, all feedback is welcome.
Have fun!
Les structures en C# sont amusantes - Partie 3/9: Initialisation des champs dans les structures
- Les structures en C# sont amusantes
- Brève introduction aux Value Types vs Reference Types.
- Initialisation des champs dans les structures (cet post).
- Comportement des constructeurs dans structures.
- Des autres scénarios dans lesquels le comportement des constructeurs de structure peut vous surprendre.
- Struct avec des valeurs d'argument par défaut dans les constructeurs, ou, n'êtes-vous pas encore confus ?
- Le modificateur `required`de C # 11 ne sauvegardera pas votre
c*lemploi. - Structure utilisée comme valeurs d'argument défaut.
- Bonus: L'evolution des structures en C#.
Poursuivant notre série sur les types de valeur (Value Types), étant donné le code ci-dessous, qu'attendez-vous qu'il imprime (je vous recommande d'essayer de répondre avant de l'exécuter):
Si vous avez répondu 0 (zéro), vous l'avez cloué et avez probablement déjà une bonne compréhension de la façon dont .NET/C# gère l'instanciation de type valeur/l'initialisation de champ; par contre, si vous avez répondu 32, vous avez peut-être été trompé.
Dans cet article, je vais aborder brièvement l'un des aspects qui conduisent à ce comportement : l'initialisation des champs en .NET, ou pour être plus précis, en C#.
D'une manière trop simpliste, chaque fois que le compilateur C# trouve une initialisation de champ, il déplacera simplement le code d'initialisation vers les constructeurs, c'est-à-dire que l'initialisation d'un champ équivaut à définir sa valeur dans les constructeurs (les champs statiques sont initialisés dans les constructeurs statiques), donc étant donné le code ci-dessous :
le compilateur C# le traitera tel qu'il a été écrit ainsi :
ce que vous pouvez confirmer dans l'IL généré ci-dessous, mais gardez ce qui suit à l'esprit si vous n'êtes pas familier avec le code IL :
- Il ne faut pas se laisser intimider par son apparente complexité.
- J'ai inclus des commentaires pour souligner les éléments clés.
- J'ai omis certains détails moins cruciaux.
- Il n’est pas nécessaire de saisir tous les détails pour comprendre le concept principal.
Les lignes 6~22 et 25~36 définissent le constructeur ne prenant aucun paramètre et celui prenant un int (Int32); notez que le code lié à l'initialisation du champ (`f = 42`) a été introduit dans les deux (lignes 9~11 et 29~31).
Dans le prochain article, nous commencerons à explorer le comportement du constructeur de structure, c'est-à-dire la deuxième partie du puzzle qui explique pourquoi le programme en haut de l'article imprime 0.
Comme toujours, tous les commentaires sont bienvenus.
Amuse toi!
Jul 31, 2023
Structs in C# are fun - Part 2/9: A brief introduction to Value Types vs Reference Types
- Structs in C# are fun
- Brief introduction to Value Types vs Reference Types (this post)
- Field initialization in structs.
- Constructors and struct behavior.
- Other scenarios in which struct constructors behavior may surprise you.
- Struct with default argument values in constructors, a.k.a, are you not confused yet ?
- `required` feature from C# 11 will not save your
a**job. - Struct used as default argument values.
- Bonus: Struct evolution in C#.
Since the first oficial release (version 1.0, back in January/2002) of C#, developers have been faced with a decision when introducing new types: declaring it as a class (a reference type) or a struct (a value type), represented in the .NET type system by System.Object and System.ValueType respectively.
Picking one over the other has non trivial implications in usability, performance, extensibility to list a few. In this post I want to briefly cover the main differences (more details will be presented in future posts) and clarify one misconception (which I am probably guilt of contributing to disseminate). So without further ado lets get into the most important distinction about the two...
Reference type vs Value type semantics
The most important characteristic distinguishing these 2 kind of types relates to equality and assignment/parameter passing are behaviour. The table below shows these differences (assuming the types in question does not overloads Equals() method or ==/!= operators):
| Value Type | Reference Type | |
|---|---|---|
| Assignment semantics |
by value, i.e, the instance contents is copied leaving two independent copies. |
by reference, i.e, assignment just copies a reference and changes through any of the references will be observed when accessing the object through the other one. |
| Equality (Identity semantics) |
two instances are equal if they are instances of the same type and all its fields are equal. | two instances are equal if they reference the same object (i.e, exact same reference) |
In order to make it easier to visualise, imagine the following code:
After running the code through line 15, we can represent the memory used by v1 and v3, in an overly simplified way, as something like:
i,e, variable v1 is stored at address 0x100 while v3 at address 0x400. Notice though that v3 does not store the actual instance data of the AReferenceType object. Instead it stores a reference (or, in an oversimplification, a pointer) to the actual object allocated at address 0x1000. In contrast, AValueType instances stores its data inline.
If we inspect the memory state when program reaches line 19, we'd observe something like:
Notice that both variables (v1 & v3) had its contents copied to the newly declared ones (v2 & v4) but since v3 is a reference type, copying its value means copying a reference, a fact that will become evident later.
When the code prints the IntValue fields from v1 & v2 it is evident that the same value will be displayed but after storing the value 71 in v2.IntValue ( at line 21), the memory will look like:
so line 22 will print the values 42 & 71, or, in other words, v1 & v2 are independent of each other.
Reference types work differently; let's start with line 25 in which v3 and v4 IntValues are displayed; in order to figure out which values will be passed to Console.WriteLine() method, first the value of v3 (i.e, 0x1000) is read from the location at address 0x400 (v3) and then the contents at that address (actually the four bytes that makes up an int in C#) is read, producing the value 42; next the same process is repeated for v4; since v4 references the same object as v3 (0x1000) that will produce the same result.
Since a similar process is applied when changing reference type state, after executing line 26, the memory will look like:
and line 27 will print 71 & 71 i.e, changes applied to v4 are observable through v3.
Misconceptions
Over the years I have seem multiple articles, interviewes and even some books claiming that one of the main difference between value types vs reference types is that value types are always stored on the stack while reference types are always stored in the managed heap (as I mentioned above, most likely I am guilt of propagating this misconception also :().
This misconception is so spread that Eric Lippert (which worked as one of the designers of C# in the past) wrote 2 blog posts to debunk it.
As Eric mentions, the fact that value types are usualy allocated on the stack is an implementation detail, but IMO, one that will hardly change; that said this implementation behavior is important in scenarios where keeping heap allocations (and consequently GC pressure) low is crutial to achieve predictable performance characteristics.
As always, all feedback is welcome.
Have fun!




