
How can a C# anonymous class implement an interface?
Need an explanation of this code. Anyone?



Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Jason BowersPosted Nov 16, 2014, 10:12 AM
Arunava BhattacharjeePosted Sep 11, 2014, 7:30 AM
deepak vermaPosted Sep 4, 2014, 3:41 AM
when the reference id of child class put into the reference variable of parent class or Interface .then this concept is called Dynamic Binding.
ITest InterfaceWithoutObject = new Test();
//parent // Child class
VulpesPosted Aug 30, 2014, 9:03 AM
You can then assign instances of classes or structs which implement the interface to the variable, parameter or return value and invoke interface methods/properties using that variable etc.
The advantage of this is that it enables you to write generic code which applies to any type which implements an interface even if those types otherwise have no relation to each other.
Sahil SharmaPosted Aug 30, 2014, 8:06 AM
ITest InterfaceWithoutObject = new Test();
I'm little confused as ITest is actually an interface and is getting instantiated by Test(). A general rule is we cannot create an object of interface but this code builds successfully. I did a little googling and found that we can instantiate an interface using anonymous class. Could you explain more?
VulpesPosted Aug 30, 2014, 7:26 AM
This class also has a private instance field, InterfaceWithoutObject, of type ITest and is initialized by assigning a new Test object to it.
However, whilst the code compiles, if you try to run it and include a line such as this:
Test t = new Test();
then you'll find that execution ends with a StackOverflowException.
This is because the code creates an infinite loop - when a Test object is created, the private field is initialized creating another Test object, and so on until the stack overflows.
BTW, you're right that an anonymous type can't implement any interfaces.