Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning events in object initializer

Tags:

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?

like image 551
Max Avatar asked Oct 22 '10 03:10

Max


People also ask

What is object initializer?

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.

What is object initialization why it is required?

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.

How do you assign initial values to object properties when an object is created?

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.

What are Initializers syntax and give an example?

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.


1 Answers

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), }; 
like image 150
Drew Noakes Avatar answered Oct 02 '22 13:10

Drew Noakes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!