Optional parameter in the method, not a compile-time error with Rectangle

I have a method where I would like to use the optional Rectangle parameter with the default value (1,1,1,1).

 void Method(int i, int j = 1, Rectangle rect = new Rectangle(1,1,1,1)) {} //error 

How do i solve this? (I use XNA, so it is Microsoft.Xna.Framework.Rectangle .)

+6
source share
2 answers

Not. optional parameters must be compile-time constants, and new Rectangle(1,1,1,1) not a compile-time constant.

You can have two method overloads, one of which does not have a rectangle:

 void Method(int i, int j = 1) { Method(i, j, new Rectangle(1,1,1,1)) } 
+8
source

I found a better way:

 void MyMethod(string someString, Rectangle rect = default(Rectangle)) { if (rect == default(Rectangle)) rect = new Rectangle(1, 1, 1, 1); } 

There can only be one problem: when the default values โ€‹โ€‹and the passed values โ€‹โ€‹match, this will be true for == default(T) . But one way is to pass null and check for this to set it as the default for type ot.

+1
source

Source: https://habr.com/ru/post/923894/


All Articles