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?
There are two things the class needs in order to be eligible for that syntax:
IEnumerable
(or some other interface that implies IEnumerable
- it could also inherit from a base class that implements IEnumerable
)Add(...)
method capable of receiving an int
valueAny 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.
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