Posted by: tzuhsun | April 21, 2009

TryParse – out parameter cannot work with Property

Today I facing the exact situation written in reference #1, I tried to pass the property to TryParse out parameter.

Below is the sample code:

int i;

public int I
{
  get;
  set;
}

int.TryParse(str, out I);   // pass I (not i) as out parameter

But I got this error message:

A property or indexer may not be passed as an out or ref parameter.

Till now I cannot get any satisfactory explanation about this error, however I think the most acceptable answer for now is from reference #2.

The fact that a property looks and feels like a variable is deceiving. When compiled, a property becomes two methods: one for the Getter and one of the Setter. This is why the property fails when you try to use it in TryParse().

Solution is simple, just place the original variable as out parameter.

This question make me need to understand MSIL one day to find out what happen inside there…

Reference:

  1. Mano’s Tech Blog – Different ways to convert string to an integer in C#
  2. Why TryParse Can’t Get Property?

Keyword: Accessor, get,set,getter,setter,error


Responses

  1. You should download .NET Reflector disassemble above example. You will have a clear picture why it doesn’t work.


Leave a response

Your response:

Categories