Ari
Ari

Reputation: 3669

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.

Upvotes: 3

Views: 133

Answers (5)

Adam Houldsworth
Adam Houldsworth

Reputation: 64487

The syntax:

var d = (IDisposable)foo;

Is called an Explicit Cast.

The syntax:

((IDisposable)foo).Dispose(); 

Explicitly casts foo into a temporary variable and calls Dispose on it (do note, a temporary variable is used here but you cannot see it, it is created by the compiler).

The brackets tell the compiler the order of precedence on the actions. In this case, it says to cast the variable to IDisposable before resolving the Dispose call. Because it is done before, the compiler now knows to resolve Dispose on a variable of type IDisposable.

You can see this behaviour in other forms:

(foo as IDisposable).Dispose();

Or:

string s = null;

while ((s = Console.ReadLine()) != null)
{
}

My first example casts using the as operator in the same manner as your own cast (in-line). My second example sets a variable s before proceeding to test it against null.

My point being, none of these would compile without the use of brackets to define the boundaries.

Upvotes: 2

Eugen Rieck
Eugen Rieck

Reputation: 65274

  • Start with foo
  • Prefix it with (IDisposable) to cast it to the requested interface
  • Put this in brackets to tell .net that foo is the thing to be cast, not the result of foo.Dispose()
  • Now add .Dispose() to address a method of the interface

Upvotes: 2

andrews_nz
andrews_nz

Reputation: 185

The inner set of parentheses around IDisposable turn it into a cast, and then the outer set of parentheses ensure that the cast occurs before the call to Dispose().

Upvotes: 0

ChrisNel52
ChrisNel52

Reputation: 15143

It's just a shortcut when doing the conversion to IDisposable.

This...

((IDisposable)foo).Dispose(); 

is the same as this...

IDisposable i = (IDisposable)foo; 
i.Dispose();

Upvotes: 0

Dan
Dan

Reputation: 45752

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.

Upvotes: 3

Related Questions