Can I use user defined type, say a class inside using block ? When I used:
It said, I need to inherit IDisposable and implement Dispose method. I inherited and tried to define Dispose method, I couldn't. It shows me its not public or something :( Please help me understand this with a small code on how can I achieve it.
If I create an instance of a class inside the "using" brackets, although the scope of this variable is only within that using block, why the heck I cannot create another instance of the same class with the same variable outside the using ? I see no good reason for that :( Is my reasoning correct ? But I could use the same variable for instantiating another class outside the using(Is that ok to do ? As I see no compile errors), although I am well aware that we should practise coding guideline (But conceptually I am seeking logic)....
Please help, I am new to C#
The whole point of the using statement is to call the Dispose method specified in the IDisposable interface.
And yes, when implementing an interface, either the method needs to be public or you need to use explicit interface implementation:
// Via a public method
public class Foo : IDisposable
{
public void Dispose()
{
// Stuff
}
}
// Via explicit interface implementation
public class Bar : IDisposable
{
void IDisposable.Dispose()
{
// Stuff
}
}
There's nothing specific about IDisposable here - it's just normal interface implementation.
You shouldn't implement IDisposable just for the sake of it though - the idea is that it should be cleaning up for you - if you don't have any clean-up to perform, you don't need the using statement either.
As for the second point: you're simply not allowed to declare a local variable with the same name as another local variable which is still in scope. It would be very confusing to read, hence it's prohibited. From section 8.5.1 of the C# spec:
The scope of a local variable declared in a local-variable-declaration is the block in which the declaration occurs. It is an error to refer to a local variable in a textual position that precedes the local-variable-declarator of the local variable. Within the scope of a local variable, it is a compile-time error to declare another local variable or constant with the same name.
Note that you can still have the same local variable name twice in one method, provided they're not both in scope at the same time:
void M()
{
using (Stream x = ...)
{
}
using (Stream x = ...)
{
}
for (int x = 0; x < 10; x++)
{
}
// Block introduced just for scoping...
{
string x = "";
...
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With