Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional parameter in method not compile-time constant error with Rectangle

I have a method where I'd like to use a Rectangle optional parameter with default value of (1,1,1,1).

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

How do I resolve this? (I'm using XNA, so it's a Microsoft.Xna.Framework.Rectangle.)

like image 565
user1306322 Avatar asked Aug 27 '12 17:08

user1306322


2 Answers

You don't. optional parameters must be compile time constants, and new Rectangle(1,1,1,1) isn't a compile time constant.

You could have two method overloads, one that doesn't have a rectangle:

void Method(int i, int j = 1) 
{
    Method(i, j, new Rectangle(1,1,1,1)) 
}
like image 178
Servy Avatar answered Sep 22 '22 11:09

Servy


I just found a better way:

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

There may only be one problem: when the default and passed values match, it will still be true for == default(T). But one workaround is to pass null and check for that to set it to default value ot type.

like image 24
user1306322 Avatar answered Sep 18 '22 11:09

user1306322