
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.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
VulpesRank #55 · 29.2K reputationPosted Aug 30, 2014, 3:26 AM EDT
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.
Sahil SharmaRank #742 · 3.1K reputationPosted Aug 30, 2014, 4:06 AM EDT
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?
VulpesRank #55 · 29.2K reputationPosted Aug 30, 2014, 5:03 AM EDT
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.
deepak verma124 reputationPosted Sep 3, 2014, 11:41 PM EDT
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
Arunava BhattacharjeeRank #635 · 3.8K reputationPosted Sep 11, 2014, 3:30 AM EDT
Jason Bowers2 reputationPosted Nov 16, 2014, 5:12 AM EST