-1

Can I generate in C# auto-property with default value?

public class MyClass
{
     MyClass()
     {
         Reason = "my reason";
     }

     public string Reason{ get; set; }
}
Abbas
  • 14,186
  • 6
  • 41
  • 72
YAKOVM
  • 9,805
  • 31
  • 116
  • 217

3 Answers3

4

Yes, you can. Definitely. Just like you've shown it.

O. R. Mapper
  • 20,083
  • 9
  • 69
  • 114
  • What's the downvote for? (I originally wanted to post a single "Yes.", but unfortunately, SO wouldn't let me post such a short answer.) – O. R. Mapper Jan 07 '14 at 09:34
  • Didn't put the down-vote but it won't work `as shown` because the constructor is not public, so `var mc = new MyClass()` won't even compile. – Abbas Jan 07 '14 at 09:39
  • @Abbas: As explained on [MSDN](http://msdn.microsoft.com/en-us/library/ba0a1yw2.aspx), the default visibility for members is `private`, so indeed the constructor is not public. It can only be called from within the class. Where does the OP require `var mc = new MyClass();` to be compileable? – O. R. Mapper Jan 07 '14 at 09:44
  • @Abbas He's not doing `new` anywhere ... If you want to be pedantic. Anyway +1 :) – Dimitar Dimitrov Jan 07 '14 at 09:45
  • 1
    Didn't say he requires this, I was just mentioning this. But you're right in your answer and @DimitarDimitrov, didn't mean to be pedantic, I merely tried to help, +1 from me too. :) – Abbas Jan 07 '14 at 09:52
  • @Abbas Sure I get it, sorry if I sounded like a jerk, had a long day :) Cheers – Dimitar Dimitrov Jan 07 '14 at 09:53
  • 1
    No it's good to point it out. Makes me think longer before giving comments/answers. ;) – Abbas Jan 07 '14 at 09:54
  • @Abbas: Just to be clear; it's true that a public constructor is probably desirable. But it does compile as is, and maybe the OP wants to keep the constructor private and add a static factory method instead (or just instantiate the class via reflection for some instance). – O. R. Mapper Jan 07 '14 at 09:59
  • You're absolutely right. That's why I explained you were right from the beginning and why you got the upvote from me. :) – Abbas Jan 07 '14 at 10:16
3

Yes, but to be able to create an instance from outside your class, make your constructor public.

public class MyClass
{
    public MyClass()
    {
        Reason = "my reason";
    }

    public string Reason {get; set; }
}
Abbas
  • 14,186
  • 6
  • 41
  • 72
1

You have to add a default constructor and initialize the autoproperty value.

Antonio Petricca
  • 8,891
  • 5
  • 36
  • 74