Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anonymous types (classes features)

I have one big difficulty. I got the question to answer: What features should MyClass have in order to be correct?

var myVariable = new MyClass { 25 };

I have tried to find the answer since friday but I have no results yet. Have you got any ideas about it?

like image 727
syzmon9 Avatar asked Apr 10 '16 16:04

syzmon9


1 Answers

There are two things the class needs in order to be eligible for that syntax:

  • It needs to implement IEnumerable (or some other interface that implies IEnumerable - it could also inherit from a base class that implements IEnumerable)
  • It needs to implement an Add(...) method capable of receiving an int value

Any one of the following class declarations would 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 more types as well that the compiler can automatically cast the int value to, the above are just 3 different examples.

like image 138
Lasse V. Karlsen Avatar answered Sep 27 '22 22:09

Lasse V. Karlsen