Fortsätt till huvudinnehåll

Inlägg

I have moved!

From now on you can find my blog at ericbackhage.net
I will leave this blog as it is.
Now go check out my new blog!
Nya inlägg

C# Enum as bit field

Bit field enum Whenever you wish to express combinations of properties of an object, bit fields are a good way to accomplish this. As a simple example, consider a file in the file system. It can be Readable, Writable, Hidden or a combination these.

The different attributes can be defined as an enum:

[Flags]
public enum FileAttribute
{
  None      = 0b0000;
  Readable  = 0b0001;
  Writeable = 0b0010;
  Hidden    = 0b0100;
}

To indicate that this enum is expected to be used as a bit field I have defined it with the FlagsAttribute. It is important to understand that the FlagsAttribute does nothing more than making some changes to how the ToString method of the enum works, making it possible to print out all flags. It does not introduce any validation or special treatment of the enum in any other way.

I have defined the values of the different fields of the enum using binary representation, this should make it even more clear that this is a bit field and which bit that maps to which property.

C# Deconstruct and Discards

Deconstruct and Discards In the last post I mentioned the Deconstruct method and how it should not be mixed up with a Destructor. In this post I will show some examples and how you can use Deconstruct and especially in combination with something called Discards.

The Deconstruct method can be defined within a class to provide a way to retrieve a Tuple of the data that makes up the type and Discards can be used by the caller to effectively ignore the members of the Tuple that aren't of interest.

Sounds complicated? Hopefully the examples below will clear things out.
Implementing the Deconstruct method Let's start with a simple container class holding attributes of a file in the filesystem.

public class FileInfo
{
  public string Name { get; }
  public int SizeInBytes { get; }
  public bool ReadOnly { get; }

  public FileInfo(string name, int sizeInBytes, bool readOnly)
  {
    Name = name;
    SizeInBytes = sizeInBytes;
    ReadOnly = readOnly;
  }

  public void Deconstruct(out string na…

C# Finalize, Dispose, and Deconstruct

Introducing the Concepts It is easy to get a bit confused when trying to figure out what resources you need to free explicitly and how to release the resources that your class has created or is holding references to. You will find that there is something called Finalizer, a clean-up pattern called The Dispose Pattern, and a special Deconstructmethod that you can declare. In most cases though, you don't have to do anything and just let the Garbage Collector (GC) do its thing.

However, if your class allocates unmanaged memory, open file handles, network sockets, database connections or similar, you need to ensure that these are properly closed and freed before the references are removed. I will go through the different concepts and hopefully clear out how to ensure that all resources are properly freed in your application.
The Deconstruct method You might say that it is incorrect to even mention the Deconstruct keyword/method in this post, since it actually have nothing to do with …

When to use out parameters in C#

The out keyword In C# you can use the out keyword to define output parameters in your method signature. For example, the Int32.TryParse method in the System namespace has the following signature:

public static bool Int32.TryParse(string s, out int result)

From this you can read out that the TryParse method returns a boolean but also provides a result as an out parameter. The boolean will indicate whether it was possible to parse an integer value from the string s and store it in the result variable.

You can call the TryParse method like this:

if (Int32.TryParse(str, out var result))
{
    Console.WriteLine($"The result is: {result}");
}
else
{
    Console.WriteLine("Parsing failed");
}
When is it a good idea to use out parameters? Most of the time the use of out parameters adds complexity to your program. It will make the source code harder to follow since anyone reading the code will have to juggle several return values instead of just one.

One of the most important jobs…

C# Delegates, Action, Func, or Predicate

Introduction As a previous C developer I am used to working with function pointers and I found the C# Delegates quite easy to work with in comparison. One thing that made me a bit confused initially however were the Delegate types defined in the .NET framework. Why would I want to bother with Actions, Funcs, and Predicates? After reading up on them I almost never define custom Delegates anymore. I will try to explain their use cases below.
Delegates A Delegate in C# is similar to a function pointer in C or C++. You can always define a custom Delegate that matches any method signature you want. However, the .NET Framework defines a number of Delegates you can use so that you don't have to define your own. These Delegates are grouped into three different Delegate groups, Actions, Funcs, and Predicates.
Actions An Action is, as the name implies, a Delegate that encapsulates a method that performs an operation and where you expect no result to be returned. The ActionDelegate takes …

Override the Object.GetHashCode method, why you should bother

When you design a class you sometimes want to override the Equals method in order to use some internal fields to determine if two instances of the class are equal.

For example let's assume that you have implemented a class Money that has two fields, one named _amount of type decimal and another one called _currency of type string. You decide that two objects of type Money are equal if and only if the amount and currency fields have the same values.

The implementation of Equals looks like this:

public override bool Equals(object obj) { if (obj is Money other) { return _currency.Equals(other._currency, StringComparison.Ordinal) && _amount.Equals(other._amount); } return false; }
You then notice that you get a warning during compilation,Warning CS0659 'Money' overrides Object.Equals(object o) but does not override Object.GetHashCode(). So what is this all about?

If you look into it a bit you will find that there is a rule saying that if two objects…