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.
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:
Original Answer
Automatically implemented properties can be initialized in the class constructor, but not on the propery itself.
…or you can use a field-backed property (slightly more work) and initialize the field itself…
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.