About in parameter modifier on value type, properties and defensive copy

in parameter modifier was introduced in C# 7.2. It lets you pass (value) types by reference but at the same time protect you against modifying the actual instance.

Here is what What's new in C# 7.2 says about it:

The in modifier on parameters, to specify that an argument is passed by reference but not modified by the called method.

Basically compiler protects you against modification of the instance in two ways:

  • when you try to change a field directly compiler will throw an error
  • when you call an instance method, compiler will create a defensive copy of the instance and run that method on the copy

But what happens when calling instance properties? Will compiler create a defensive copy as well? Even for autoimplemented getters? That's the question I've got on my presentation and I wasn't sure about it. On one hand properties in general can implement modification code and in that sense they aren't safe just like methods aren't. On the other hand autoimplemented getters don't implement any modification code.

If I had to guess I'd say there is no need for defensive copies when dealing with autoimplemented getters, while in other cases compiler will resort to defensive copies.

After few experiments and using Reflector to inspect the generated code it turns out that compiler will use defensive copies with properties always, even with autoimplemented getters. You can also check it out with SharpLab.io, which is a great way into digging into (experimental) C#.

Looks like there is some room for improvement.

Mono, Docker, 3.14, WebAPI on NTK 2016

This year I’ll be presenting at Microsoft’s NT Konferenca as I do every year.

As the topic I’ve picked my experience of using Docker I gathered from a real world example. I’ve been building an application that is a combination of PostgreSQL database, Mono/NGINX/WebAPI on server and UWP/Windows10 on client. Server side supports various OS. Target is Linux but it should run on Windows without issues. The combination of server OS and server tools choice drives costs down significantly on one hand and makes it versatile on the other.

Docker helps a lot through the development and final deployment in production. And that’s what talk is all about. 3.14 will play a role as well – showing that there is almost no HW restriction for such a combination on server side. We’ll build and deploy the application through rich demos.

See you there, Monday at 9:00.

Strong typing DisplayAttribute reference to Resources

Let’s say there is a decorated member with DisplayAttribute in code, i.e.:

public enum SomeEnum
	[Display(Name = "ResourceKey", ResourceType=typeof(Resource)]

That’s all right except for one problem. If Name is mistyped or given resource key is latter changed then DisplayAttribute will point to an incorrect value and compiler won’t help. Resources designer doesn’t help as well, at least indirectly, because it doesn’t generate externally usable key names. It generates strong typed getters though, like:

internal static string ResourceKey {
        get {
             return ResourceManager.GetString("ResourceKey", resourceCulture);

So, these getters are the only strong typed artifact that can be used to achieve strong typed reference. Luckily there is one C# (also VB) feature that was introduced in 6.0 and it is very useful in improving strong typed aspect of code. it is nameof keyword. it is evaluated at compile time and replaces the given expression with a string representation.

In other words, the sample above can be rewritten in strong typed manner:

public enum SomeEnum
	[Display(Name = nameof(Resources.ResourceKey), ResourceType=typeof(Resource)]

This way the name is guaranteed to match since it is checked at compile time. So, no more mismatch between the key name and reference to it.

Of course, nameof can be used in many other places. Most notably in INotifyPropertyChanged/MVVM scenario.

Use async keyword only when required

While async keyword is very useful it shouldn’t be used when it isn’t required. Imagine this method

public async Task DoSomethingAsync()
	await Task.Delay(1000);

The method works but it has too much code generated unnecessarily. The thing is that async triggers a lot of code generation at compile time that is invisible at design time. When using .Net Reflector, compiled code looks like:

[AsyncStateMachine(typeof(<dosomethingasync>d__1)), DebuggerStepThrough]
public Task DoSomethingAsync()
	<dosomethingasync>d__1 stateMachine = new lt;dosomethingasync gt;d__1 {
		<>4__this = this,
		<>t__builder = AsyncTaskMethodBuilder.Create(),
		<>1__state = -1
	stateMachine.<>t__builder.Start<<dosomethingasync>d__1>(ref stateMachine);
	return stateMachine.<>t__builder.Task;

private sealed class lt;dosomethingasync>d__1 : IAsyncStateMachine
	public int <>1__state;
	public Program <>4__this;
	public AsyncTaskMethodBuilder <>t__builder;
	private TaskAwaiter <>u__1;

	private void MoveNext()
		int num = this.<>1__state;
			TaskAwaiter awaiter;
			if (num != 0)
				awaiter = Task.Delay(0x3e8).GetAwaiter();
				if (!awaiter.IsCompleted)
					this.<>1__state = num = 0;
					this.<>u__1 = awaiter;
					Program.<dosomethingasync>d__1 stateMachine = this;
					this.<>t__builder.AwaitUnsafeOnCompleted gt;taskawaiter program.="" ,=""><dosomethingasync>d__1>(ref awaiter, ref stateMachine);
				awaiter = this.<>u__1;
				this.<>u__1 = new TaskAwaiter();
				this.<>1__state = num = -1;
			awaiter = new TaskAwaiter();
		catch (Exception exception)
			this.<>1__state = -2;
		this.<>1__state = -2;

	private void SetStateMachine(IAsyncStateMachine stateMachine)

I won’t dig into what’s actually generated at this point, but while this code is perfectly functional and correct, it is all for nothing in this simple case. Since the only asynchronous operation is the last one, the original method can be easily rewritten as:

public Task DoSomethingAsync()
	return Task.Delay(1000);

This way it works the same except for the missing pile of generated code.

So, when there is a single asynchronous operation inside the method and no code is executed after it, the async (and await) keyboard can be omitted and you’ll save yourself from too much unnecessarily generated code plu the application will run a bit faster.

Porting a .net application to Linux/Mono/MonoDevelop

I have a small .net application that I wanted to run on Linux since it is a deamon/service sort of app. Basically is an app that peridically retrieves data from a REST service and stores it to a PostgreSQL database using LLBLGenPro 5.0 CTP2. So I created a .net 4.6.1 console application that uses HttpClient/ModernHttpClient package, NLog package for logging and System.Collections.Immutable package for immutable collecitons obviously. That was on Windows using Visual Studio 2015. After I added all the necessary code it run perfectly well on Windows.

Then I tried to open the same solution on Linux. I cloned the repository and opened it in MonoDevelop 5.10/Mono 4.2.1 (both latest). And it didn’t work out of the box. I stumbled over several issues I will describe here.

.net version

MonoDevelop doesn’t work with anything over .net 4.5 for the time being due to the MSBuild thing – at least that was the complaint.

Hence I downgraded my project to .net 4.5. No problems since I didn’t use anything .net 4.6ish.


It won’t install System.Collection.Immutable package because System.Linq package (which System.Collection.Immutable depends on for some reason) won’t install unless NuGet Package Manager is 3.0 or newer. MonoDevelop uses NuGet Package Manager 2.8.7. While this is only a NuGet Package installation issue, it is annoying. First, because System.Collection.Immutable doesn’t really require System.Linq package on Mono/.net 4.5 and next becuse it isn’t smooth as it should be. Funny thing is that at NuGet web page it says that System.Collection.Immutable requires NuGet 2.8.6 or higher. I guess it should be 3.0 or higher since a package that it depends on requires it.

Hence I dropped System.Collection.Immutable package which wasn’t difficult because I wasn’t using it extensively. Hopefully MonoDevelop catches up with NuGet and that is fixed.


ModernHttpClient speeds up communication since it uses native networking libraries. However it won’t work on Linux.

Dropped it since it doesn’t affect the functionallity at all.


I had configure NLog though nlog.config file. And it works on Windows perfectly. Hower when run on Linux I didn’t get any output whatsoever. Just like there was no configuration file. As a Windows guy I was a bit puzzled why. Since NLog is open source, I downloaded the code and tried debugging. Sadly MonoDevelop didn’t allow me to step into NLog code for some reason but luckily old school “Console.WriteLine” approach worked as usual. After some strategically placed Console.WriteLine calls within NLog library I found the reason, which might be apparent to a Linux guy. Bloody file name casing. I was using nlog.config and Windows doesn’t care about file name casing.

On Linux file name casing does and thus changing the name to NLog.config did the trick.

Linux specific addition

If app wants to gracefully handle SIGTERM signal (like when somebody/something tries to kill it) it might use UnixSignalWaiter NuGet package. While only at version 0.0.1 it seems to work just fine. It is also safe to use it on non-Linux systems where it does nothing (one might also check whether the feature is supported).


If .NET Core has proper database support (PostgreSQL in my case, but more more importantly LLBLGenPro doesn’t work due to lack of ado.net support – I don’t know about you but for me the proper ado.net stack on server is one of the most important aspects) I’d try to use it as well. But since it doesn’t, well, someday in the future I guess.

Anyway, after learning all the problems and the workarounds above I feel more confident in my Mono/Linux skills and the application compiles fine and works as expected. I also think that Xamarin/mono guys are doing really great job. Kudos.

Did I mention that I’m using Docker to run the application? I guess that’s a topic for a future post.

Thinking about delayed getters on properties in C#6.0 or after that

Here is a typical scenario where one postpones property value creation until the property getter is accessed:

private SomeType something;

public SomeType Something 
     if (something == null)
       something = new SomeType();
     return something;

This pattern is usually applied when property SomeType is rarely used. It doesn’t make much difference on desktop applications (unless there is a ton of these properties) but it might make some performance gains on mobile apps where performance is more critical and memory is less abundant. Of course, one could use Lazy<T> but that would create an instance of Layz<T> instead plus the instance of SomeType eventually.

Now, there is a Expression bodies on property-like function members proposition for C# 6.0 that allows getter-only properties to be implemented with an expression, i.e.:

public string Name => First + " " + Last;

However, full lambdas aren’t supported thus something field can’t be assigned and we’d end up with a new SomeType instance each time.

So, I was thinking a bit about how that could be implemented and here is my proposition for delayed getter-only property assignment:

public SomeType Something => const new SomeType();

This would cause the instance of SomeType to be created only when getter is first time accessed and after that the same instance would be used just like in the original example.

What do you think?