Search code examples
c#syntaxparentheses

Can somebody explain the parts of this syntax, and how it would be used?


While going through some tutorials, I have encountered lines such as this:

((IDisposable)foo).Dispose();

Ignore the specific reference to Idisposable. I am curious as to why the parentheses are set the way they are and what they contain / do. I'm sure this is a very simple question to answer, but I have been unable to find the answer through searching, due to the generics of such a syntax. Help would be much appreciated, thank you.


Solution

  • The first set of parentheses are casting it to an IDisposable object. For example

    Object foo = new Object();
    IDisposable ID;
    

    Now ID = foo will give an error but ID = (IDisposable)foo will work.

    The second set of parentheses allows you to access methods and properties of IDisposable objects, in this case the Dispose() method. If you type it out you will see that only once you have enclosed the second set of parentheses will intelisense show you the methods and properties of IDisposable objects.