Why isn't it possible to assign events along with properties in object initializers in C#? It seems to be so natural to do so.
var myObject = new MyClass() { Property = value, Event1 = actor, // or Event2 += actor }; Or is there some trick that I don't know of?
An object initializer is an expression that describes the initialization of an Object . Objects consist of properties, which are used to describe an object. The values of object properties can either contain primitive data types or other objects.
In object initializer, you can initialize the value to the fields or properties of a class at the time of creating an object without calling a constructor. In this syntax, you can create an object and then this syntax initializes the freshly created object with its properties, to the variable in the assignment.
To create an object of a named class by using an object initializer. Begin the declaration as if you planned to use a constructor. Type the keyword With , followed by an initialization list in braces. In the initialization list, include each property that you want to initialize and assign an initial value to it.
C# - Object Initializer Syntax In the above example, Student class is defined without any constructors. In the Main() method, we have created Student object and assigned values to all or some properties in the curly bracket at the same time. This is called object initializer syntax.
This didn't make C# 6 or C# 7 (since the original question), however it hasn't been decided against. There is an issue on GitHub that tracks the language proposal. You can vote for it there, as well as follow links into previous discussion around the feature.
https://github.com/dotnet/csharplang/issues/307
If you'd like to see this feature, add a thumbs-up to the issue to help raise its visibility.
The proposed syntax is:
var timer = new DispatcherTimer { Tick += delegate {}, Interval = TimeSpan.FromSeconds(1d), };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With