Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Should I use out or ref to get this struct back?

I'm not sure of the best way to ask this question, so I'll start with an example:

public static void ConvertPoint(ref Point point, View fromView, View toView) {
    //Convert Point
}

This call is recursive. You pass in a point, it converts it relative to fromView to be relative to toView (as long as one is an ancestor of the other).

The call is recursive, converting the point one level at a time. I know, mutable structs are bad, but the reason I'm using a mutable point is so that I only need to create a single point and pass it along the recursive call, which is why I'm using ref. Is this the right way to go, or would it be better to use an out parameter, or simply declare the method to return a point instead?

I'm not very familiar with how structs are handled as opposed to classes in these circumstances. This is code being ported from Java, where point obviously had to be a class, so it made sense to use the same temporary point over and over rather than create a new point which had to be garbage collected at every call.

This may be a confusing question, and to heap on some more confusion, while I'm at it, should I keep a temporary static Point instance around for quick conversions or would it be just as simple to create a new point whenever this method is called (it's called a lot)?

like image 901
Ed Marty Avatar asked Dec 16 '22 15:12

Ed Marty


1 Answers

Fretting over the garbage collector is never not a mistake when dealing with short-lived objects such as the Point, assuming it is actually a class. Given that this is C#, it is likely to be a struct, not bigger than 16 bytes. In which case you should always write the method to return a Point. This gets optimized at runtime, the struct fits in cpu registers.

Only ever consider passing structs by ref when they are large.

like image 117
Hans Passant Avatar answered Dec 21 '22 23:12

Hans Passant