Question

If you have an immutable type like this:

struct Point3
{

}

and a member inside like origin:

public static const Point3 Origin = new Point3 (0,0,0);

should you use:

new Point3 (0,0,0)

?

It seems to me that since the type can not be changed, why have many origins that are essentially the same thing? Like we never change 0, right?

How to achieve the same thing for immutable types?

Was it helpful?

Solution

public static readonly Point3 Origin = new Point3(0,0,0);

OTHER TIPS

As Andrew mentioned, you can't use const for this because it's not a compile-time constant.

Note that if you are going to use a constructor repeatedly, you'd be better off (from a performance point of view) calling

new Point3()

than

new Point3(0, 0, 0)

The compiler knows that the first version is just going to blank out memory, and doesn't need to call any code.

However, I'd go along with providing an Origin member and using that everywhere instead, where possible :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top