Answered by:
auto implemented properties

Question
-
Hi,
how can I use auto implemented properties on a field and initial it to some value at the same line?
When I init a field on a declaration line I can use only regular c# properties?
Regards
Sunday, June 13, 2010 7:04 PM
Answers
-
C# does not support initalizaton for automatic properties so you'll have to set them in your constructor or use something like this , strangely enough this feature is supported without any hacky workarounds in vb.net 10!
- Marked as answer by elad2109 Sunday, June 13, 2010 10:04 PM
Sunday, June 13, 2010 9:22 PM -
You don't need reflection to initialize a property.
class MyClass { public string MyAutoProperty { get; set; } public MyClass() { MyAutoProperty = "My initial value"; } }
- Marked as answer by elad2109 Monday, June 14, 2010 11:25 AM
Monday, June 14, 2010 9:09 AM
All replies
-
When intitializing a field, you can only use static methods, fields or properties. Being automatic has no relevance.Sunday, June 13, 2010 8:17 PM
-
I meant:
pubic int val {get; set;}
public int val = 5 {get; set;}
the second is illegal. right ?
Sunday, June 13, 2010 8:59 PM -
C# does not support initalizaton for automatic properties so you'll have to set them in your constructor or use something like this , strangely enough this feature is supported without any hacky workarounds in vb.net 10!
- Marked as answer by elad2109 Sunday, June 13, 2010 10:04 PM
Sunday, June 13, 2010 9:22 PM -
cool! thanksSunday, June 13, 2010 10:04 PM
-
BTW, it's a little overkill to use reflection just so you can give automatic properties default values. I'd recommend that you just convert the property to a regular property with a backing field and then initialize that field.
http://blog.voidnish.comSunday, June 13, 2010 11:04 PM -
You don't need reflection to initialize a property.
class MyClass { public string MyAutoProperty { get; set; } public MyClass() { MyAutoProperty = "My initial value"; } }
- Marked as answer by elad2109 Monday, June 14, 2010 11:25 AM
Monday, June 14, 2010 9:09 AM