Anonymous types (class functions)

I have one big problem. I had a question: what functions should MyClass have to be true?

var myVariable = new MyClass { 25 }; 

I tried to find the answer from Friday, but so far I have no results. Do you have any ideas about this?

+5
source share
2 answers

Matching this syntax requires two things:

  • It needs to implement IEnumerable (or some other interface that IEnumerable implies), it can also inherit from a base class that implements IEnumerable )
  • He needs to implement the Add(...) method, capable of accepting an int value

Any one of the following class declarations will do:

 public class MyClass1 : IEnumerable { public void Add(int i) { } public IEnumerator GetEnumerator() => null; } public class MyClass2 : IEnumerable { public void Add(double i) { } public IEnumerator GetEnumerator() => null; } public class MyClass3 : IEnumerable { public void Add(object i) { } public IEnumerator GetEnumerator() => null; } 

There are also many types in which the compiler can automatically assign the int value given above - just 3 different examples.

+5
source

It must have an Add(int) method. This is the initializer of the collection. List does it like this.

 var myVariable = new List<int> { 25 }; 
+2
source

Source: https://habr.com/ru/post/1246819/


All Articles