Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: How to set default value for a property in a partial class?

Tags:

I'm very new to C# so please bear with me...

I'm implementing a partial class, and would like to add two properties like so:

public partial class SomeModel {     public bool IsSomething { get; set; }     public List<string> SomeList { get; set; }      ... Additional methods using the above data members ... } 

I would like to initialize both data members: IsSomething to True and SomeList to new List<string>(). Normally I would do it in a constructor, however because it's a partial class I don't want to touch the constructor (should I?).

What's the best way to achieve this?

Thanks

PS I'm working in ASP.NET MVC, adding functionality to a a certain model, hence the partial class.

like image 839
Roee Adler Avatar asked Aug 13 '09 15:08

Roee Adler


1 Answers

Updated for C# 6

C# 6 has added the ability to assign a default value to auto-properties. The value can be any expression (it doesn't have to be a constant). Here's a few examples:

// Initialize to a string literal public string SomeProperty {get;set;} = "This is the default value";  // Initialize with a simple expression public DateTime ConstructedAt {get;} = DateTime.Now;  // Initialize with a conditional expression public bool IsFoo { get; } = SomeClass.SomeProperty ? true : false; 

Original Answer

Automatically implemented properties can be initialized in the class constructor, but not on the propery itself.

public SomeModel {     IsSomething = false;     SomeList = new List<string>(); } 

...or you can use a field-backed property (slightly more work) and initialize the field itself...

private bool _IsSomething = false; public bool IsSomething {     get { return _IsSomething; }     set { _IsSomething = value; } } 

Update: My above answer doesn't clarify the issue of this being in a partial class. Mehrdad's answer offers the solution of using a partial method, which is in line with my first suggestion. My second suggestion of using non-automatically implemented properties (manually implemented properties?) will work for this situation.

like image 111
STW Avatar answered Oct 05 '22 00:10

STW