Using unsafe will be faster?

  • Thread starter Thread starter Abubakar
  • Start date Start date
A

Abubakar

Hi,
NOTE: in the following code Rectangle is a struct inside the System.Drawing
namespace.

I'v a following code:
Rectangle GetFillRectangle(ref Rectangle rect)
{

Rectangle newrect;
//calculate fill dimension for the rect passed and return the new one

return newrect;


}

If I write it using pointers will it be faster? Like:
unsafe Rectangle * GetFillRectangle(ref Rectangle rect)
{
Rectangle newrect;
//calculate fill dimension for the rect passed and return the new one

return & newrect;

}

My confusion: when I write the following code (using the first version of
the function):

....
Rectangle fillrect= GetFillRectangle(ref somerectangle);

fillrect, above, will get a "copy" of the newrect or just a reference of the
newrect created inside the GetFillRectangle() function? My understanding
says that it'll get a "copy" of the newrect because its a value type, and if
this is so there are actually 2 rectangle objects being created and only one
is getting used the first one gets gc. And if this all is true than if I
write the following code:
Rectangle * rect = GetFillRectangle(ref somerectangle);

rect pointer will get a direct reference to the newrect rectangle object
created inside the GetFillRectangle() function. So I'm saved from extra time
& memory that would have taken to create a copy of the rectangle object. Is
that true?
 
What you say is alright. But instead of using unsafe code, you can achieve same effect by using an out parameter.
 
oh thats greate, thanx I just forgot out, I'll use that.

Blomberg said:
What you say is alright. But instead of using unsafe code, you can achieve
same effect by using an out parameter.
 
Back
Top