Tuesday, September 27, 2016

'ref' argument is not classified as a variable

This error message which may be found in Visual Studio 2013 also appears in Visual Studio 2015 only therein it is the second of two lines of error messages. The first is:

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

 
 

Perhaps it's now a little more clear what is going wrong, eh? The problem would occur at the last line of this code for example...

var buckToothedTreeGnawers = new List<Beaver>()
{
   new Beaver()
   {
      Name = "Flotsam",
      MillimetersOfTeeth = 30
   },
   new Beaver()
   {
      Name = "Jetsam",
      MillimetersOfTeeth = 29
   },
   new Beaver()
   {
      Name = "Lagan",
      MillimetersOfTeeth = 40
   }
};
var lumber = Woods.ChopDownPine(ref buckToothedTreeGnawers[2]);

 
 

buckToothedTreeGnawers[2] will get the squiggly red line under it in Visual Studio letting you know that something is wrong and when you roll your mouse pointer over it... Voilà! There is our error! You cannot hand a ref variable into a method signature while referencing it out of a list. Whatever. I don't see why not, but then I don't make the rules. I'm not Anders Hejlsberg. Anyhow, code like this will actually work:

var flotsam = new Beaver()
{
   Name = "Flotsam",
   MillimetersOfTeeth = 30
};
var jetsam = new Beaver()
{
   Name = "Jetsam",
   MillimetersOfTeeth = 29
};
var lagan = new Beaver()
{
   Name = "Lagan",
   MillimetersOfTeeth = 40
};
var lumber = Woods.ChopDownPine(ref lagan);

 
 

I think you'll find this shortcoming won't get in your way all that much really. I only stumbled upon it today for the first time and I've written C# for ten years.

No comments:

Post a Comment