4

I want to use this as default value of class method as this code:

public class Article
 {
    public int Id;//PK
    public String Author;//can be empty=anonymous
    public int? ToPublishDate;
    public String Summery;
    public String Content;
    public int RegDate;
    public Boolean Publish;

    private Boolean write(Article article=this,long position)
    {
        return true;
    }
 }

but on this give me this error:

Default parameter value for 'article' must be compile-time constant.

Why this error occurs and how can I fix it?

Majid
  • 13,853
  • 15
  • 77
  • 113
  • may be this one help you http://stackoverflow.com/questions/2729639/setting-the-default-value-of-a-c-sharp-optional-parameter (or) http://stackoverflow.com/questions/7672005/optional-parameters-must-be-a-compile-time-constant – snowp May 03 '13 at 04:56
  • If you have a method writing to any arbitrary instance, and it does not need to involve the instance being called, you should probably be making it static! Maybe it's different in your situation, but that tends to be the convention. In other words: if `someArticle.write(otherArticle, 1)` implies it will actually involve the `someArticle` instance in its execution in some way. If `someArticle` never gets involved beyond being the instance you call that method through, it should probably just be `Article.write(otherArticle, 1)`. – doppelgreener May 03 '13 at 05:16

1 Answers1

12

You could set the default to null, and then reset its default in the method:

private Boolean write(long position, Article article=null)
{
    article = article ?? this;
}

(Note also that all non-default parameters have to come before any default ones.)

McGarnagle
  • 101,349
  • 31
  • 229
  • 260
  • 2
    +1. Also if `null` can be passed in as possible value than you'd need override instead of default parameter (`bool Write(long position){ return Write(position, this);}`) – Alexei Levenkov May 03 '13 at 04:59
  • 2
    @Alexei You mean an overload, not an override ;) – doppelgreener May 03 '13 at 05:14
  • why that error occurred? – Majid May 03 '13 at 05:28
  • 2
    @majidgeek Because `this` is not a compile-time constant. As in, when the code is compiling, `this` does not have a value yet. `this` has a value only at run-time, and its value depends on how the code is called. – doppelgreener May 03 '13 at 05:33