Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make use of reference to a variable in c#

Tags:

c#

I would like to shorten the expression like

this.GdkWindow.GetPosition(ConfigurationService.ApplicationSettings.rect1.X,
                           ConfigurationService.ApplicationSettings.rect1.Y);

to something like this.GdkWindow.GetPosition(refRect1.X, refRect1.Y) using reference to a ConfigurationService.ApplicationSettings.rect1 variable.

In C++ I am able to make use of a reference to the object (or variable) like this:

Rect& refRect1 = very.very2.very3.long_variable.rect1;
GetPosition(refRect1.x, refRect1.y);

How can I make the same in C#?

And how can I make a reference to the int variable like the following C++ code does:

int A = 5;
int& B = A;
B = 12;

Update: The GetPosition method is declared as void GetPosition(out int x, out int y). That method fills the ConfigurationService.ApplicationSettings.rect1 struct with some data. That's why i would like to use a reference.

I know I can do something like:

    var rect = new Gdk.Rectangle();
    this.GdkWindow.GetPosition(out rect.X, out rect.Y);
    this.GdkWindow.GetSize(out rect.Width, out rect.Height);
    ConfigurationService.ApplicationSettings.rect1 = rect;

but is there a way to avoid using the temporary variable? Is C# missing a feature even PHP has? Absolutely disappointed in C#!

like image 929
ezpresso Avatar asked Dec 22 '22 04:12

ezpresso


1 Answers

This should works, assuming the type of rect1 is Rect (var keyword is not liked but everybody) :

Rect r = ConfigurationService.ApplicationSettings.rect1;
this.GdkWindow.GetPosition(r.X,
                           r.Y);

Actually, this will create a copy of the struct, but should we care ? As you only want to read field, a copy can be used.

(note I'm not sure if it's a copy)

like image 189
Steve B Avatar answered Dec 24 '22 01:12

Steve B