Why you can't pass property as out or ref parameter

By: Chris Dunn

Sometimes compiler or language rules seem arbitrary, but actually make much more sense if you know why they are in place.  It's never a bad idea to peak under the hood, from time to time to get some perspective.

If you're writing a method or utilizing a method with a ref or out parameter, like TryParse, you'll soon realize that you can't pass in an object property as the out or ref parameter. You will meet with the following error "A property or indexer may not be passed as an out or ref parameter".

According to MSDN Properties are NOT variables and therefore cannot be passed as out parameters. See reference: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/out-parameter-modifier

So, just don't use a property right?  A simple solution is to use a temporary variable to store the value before assigning it to an object's property. Exactly, but the actual solution is not the topic of this post, but rather why, in the object oriented world this is not allowed. It's just another value right?

Well, actually it's not just another value. There are wonderful little things sprinkled throughout our C# world called syntactic sugar. It's very sweet but sometimes comes with some confusion about what's being sprinkled.

A property, as we define them are many times auto-implemented properties as such.

public string FirstName{get;set;}

Behind the scenes, the compiler converts this into getter and setter methods called accessors. (More Info).  It translates the above code into something like the following.

private string <FirstName>k__BackingField; 
public string get_FirstName() { return <FirstName>k__BackingField; } 
public void set_FirstName(string firstName) {<FirstName> k__BackingField = firstName; }

It makes sense when we see it but is easy to forget when looking at our own code.  It creates methods, not variables.  So it's not a simple value after all.  The C# team provides us with some language features that allow us to write cleaner, more compact code.  As nice as it is, we still have to consider the long form code under the hood.  Just some food (or sugar) for thought.

Tags: c# syntatic sugar

Copyright 2023 Cidean, LLC. All rights reserved.

Proudly running Umbraco 7. This site is responsive with the help of Foundation 5.