Pages about C#

Single-table hierarchical data in EF Core

When listing a tree of entities, the top-level list should only contain parent-less entites. Use the Where method to search for null parents.

Nested ternaries in C#

Code that is more concise than clear, more clever than readable, can hold developers back. Nested ternaries in C# are much too common for my taste.

Converting from Type to SqlDbType

The .NET type system and SQL Server types are not very easy to map to each other. In SQL, variables don't just have a type, but can also have precision and maximum length, which is not possible to translate into simple .NET types. Here I show a naïve approach at translating from one type system to another.

"Hello, World!" in C#

A "Hello, World!" program in C# can be written with a static Main method of a class, and calling the WriteLine method of the static System.Console class to send the "Hello, World!" string to the standard output stream.

Control data alignment in C# struct

Using the StructLayout and FieldOffset attributes, it's possible to control detailed data alignment when transmitting data between .NET-base and C++/C-based or assembler software.

Check if string contains a character in C#

There are multiple ways of checking if a string contains a specific character in C#. There are methods built into the String class, and there are extension methods in System.Linq.

How to add a custom header in HttpWebRequest

Adding a custom HTTP header to an HttpWebRequest object, targetting Windows Phone 7, is done through the Headers property. The good thing that it works for a lot of other .NET target platforms as well.