Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to tell which interface is returned by a method
    primarykey
    data
    text
    <p>Given this code snippet that can be readily pasted into Linqpad (or slightly modified in a Visual Studio console solution):</p> <pre><code>void Main() { var cat = this.GetCat(); var dog = this.GetDog(); cat.Think(); cat.ThinkHarder(); //dog.Think(); // Does not compile. //dog.ThinkHarder(); // Does not compile. //if ([dog is returned as ISmartAnimal]) // What to put here? ((ISmartAnimal)dog).Think(); // Compiles, runs, but shouldn't. reportTypeProperties(cat); reportTypeProperties(dog); } interface IAnimal { string Name { get; set; } } interface ISmartAnimal : IAnimal { void Think(); } class Animal : IAnimal, ISmartAnimal { public string Name { get; set; } public void Think() { } } ISmartAnimal GetCat() { return new Animal(); } IAnimal GetDog() { return new Animal(); } static void reportTypeProperties(object obj) { var type = obj.GetType(); Console.WriteLine("Type: {0}", type.Name); Console.WriteLine("Is smart? {0}", obj is ISmartAnimal); } static class ext { public static void ThinkHarder(this ISmartAnimal animal) { } } </code></pre> <p>The output of <code>reportTypeProperties</code> shows that <code>dog</code>, although returned as IAnimal, "is" an ISmartAnimal. (Same for both objects)</p> <blockquote> <p>Type: Animal<br> Is smart? True</p> </blockquote> <p>This is because <code>GetType()</code> returns the concrete type of the object, not its current interface.</p> <p>My question. <strong>Is there a way to tell that <code>dog</code> is returned as IAnimal?</strong> (see pseudocode). The compiler knows (so does quickview). Suppose I had some animal object and I wanted to inspect in runtime code whether or not I can make it <code>Think()</code>.</p> <p>Background:<br> This may seem an academic exercise. And it may seem strange to have a class (Animal) implement an interface (ISmartAnimal) that you don't want to expose always. But I ask because I encountered something similar in Entity Framework. If you want you can read about it <a href="https://stackoverflow.com/questions/9025137/when-is-objectquery-really-an-iorderedqueryable">here</a>, but it diverts to EF-specific features. If you don't want to delve into that it suffices to say that it's imperative that <code>Animal</code> implement both interfaces.</p> <hr> <p>Disclaimer:<br> "Any resemblance to real animals is purely coincidental :)"</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload