Posts

Showing posts with the label C#

C# Catching Exceptions Guideline (updated for C# 6.0)

The article proposes and summarizes guidelines for exception handling / catching exceptions. AVOID catching exceptions that you’re unable to handle fully. AVOID hiding (discarding) exceptions you don’t fully handle. DO use throw to rethrow an exception; rather than throw inside a catch block. DO set the wrapping exception’s InnerException property with the caught exception unless doing so exposes private data. CONSIDER an exception condition in favor of having to rethrow an exception after capturing one you can’t handle. AVOID throwing exceptions from exception conditional expression. DO use caution when rethrowing different exceptions. Rarely use System.Exception and general catch blocks—except to log the exception before shutting down the application. AVOID exception reporting or logging lower in the call stack. Sources: Essential .NET - C# Exception Handling, by Mark Michaelis, November 2015 Review of the details of each of the guidelines

What's new in C# 6.0: Null-conditional operators

One of the many new and nice C# 6.0 features is the Null-conditional operators. The example given in the linked presentation is the following: You want to do something as simple as raise an event, e.g. OnChanged(this, args); To be on the null pointer-safe side, you will have to make this an ugly abomination like: { var onChanged = OnChanged; if (onChanged != null) { onChanged(this, args); } } With C# 6.0 you can perform those checks easily with the so called "Elvis"-operator "?.": OnChanged?.Invoke(this, args); Sources: What's new in C# 6.0

How to read an assembly.dll.config

There is the common misconception that only a app.exe.config can be read in .NET C#. The truth is that the app.config is automatically read, while any other (correctly formed) app.config XML file can be read "manually". To open a named config file: Reference System.Configuration.dll assembly Using System.Configuration Create code like: Configuration GetDllConfiguration(Assembly targetAsm) { var configFile = targetAsm.Location + ".config"; var map = new ExeConfigurationFileMap { ExeConfigFilename = configFile }; return ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None); } Sources: stackoverflow: Reading dll.config (not app.config!) from a plugin module Keywords: .NET, C#, app.config, dll.config, ConfigurationManager