Alan Baljeu
Alan Baljeu

Reputation: 2443

Can't use ref-parameters and use generated table columns with the same data

Here's the objective. To be able to use ConvertLength with a ref parameter, and AutoGenerateColumns. But as far as I can figure, fields ("b") cannot be used to generate columns, and properties ("c") cannot be used as references. Is there a resolution?

class A
{
    public decimal b;
    public decimal c { get ; set ; }
}

void ConvertLength(ref decimal field)
{
   field = field * 2.0m;
}

class x : Form
{
  DataGridView dgv = new DataGridView();

  a[] rows = new a[5];  
  ConvertLength(ref a[0].b); 
  ConvertLength(ref a[0].c); 
  dgv.AutoGenerateColumns = true;
  dgv.DataSource = rows;
}

Upvotes: 0

Views: 33

Answers (1)

p.s.w.g
p.s.w.g

Reputation: 149020

From MSDN:

Properties are not variables. They are methods, and cannot be passed to ref parameters.

So you cannot pass A.c in to ConvertLength. You could pass b, but note that you'd have to use the ref keyword:

ConvertLength(ref a[0].b);

Note that b will also have to be accessible to class x (e.g. public or internal if x is in the same assembly). And also your ConvertLength method will need to use 2.0m as a decimal literal rather than 2.0 which is a double.

You almost never need to use ref parameters, and if you are using them, it's usually an indication of other issues (i.e. code smell). If it were me, I'd follow @Tbid's suggestion, like this:

decimal ConvertLength(decimal field) => field * 2.0m;

...
a[0].b = ConvertLength(a[0].b); 
a[0].c = ConvertLength(a[0].c); // works with properties or fields.

But if you really need to have one class that has fields for the sake of ref parameters and properties for the sake of AutoGenerateColumns, you could always do this:

class A
{
    public decimal b_field;
    public decimal b { get { return b_field; } set { b_field = value; } }

    public decimal c_field
    public decimal c { get { return c_field; } set { c_field = value; } }
}

...
ConvertLength(ref a[0].b_field); 
ConvertLength(ref a[0].c_field);

Upvotes: 2

Related Questions