Undeclare Variables in C#
Is it possible to undeclare variables i开发者_如何学Gon C#? If so, how?
close the scope (introduced with '{') that contains the variable declaration:
int c=0;
{
int a=1;
{
int b=2;
c=a+b;
} // this "undeclares" b
c=c+a;
} // this "undeclares" a
You don't take care of undeclaring in C# (I think you mean unallocating by the way, don't you?) or any other .Net languages, the garbage collector takes care of unallocating the memory associated with the variable.
For unmanaged resources (fonts, database connections, files, etc), you need to call the Dispose method, either explicitely or by placing the variable in an using block.
More information about the .Net garbage collector: http://www.csharphelp.com/2006/08/garbage-collection/
If the object is IDisposable, you can use them within the using
Block. In rest of the cases I'd go with what Luther
has mentioned.
using (Car myCar = new Car())
{
myCar.Run();
}
You don't - when a variable goes out of scope or no more references exist to it, it automatically gets garbage collected.
Why would you want to explicitly do this anyway; what's the context? Most likely you should simply be using a new variable name, or refactoring the relevant section of code into a new function.
I don't think it is possible in current languages. A plausible scenario is this:
void doSomething(String objectId) {
BusinessObject obj = findBusinessObject(objectId);
// from this point on the objectId should not be used anymore
undef objectId;
// continue using obj ...
}
Another scenario is when you implement some method from an interface, and you want to make sure that you don't use one of the parameters, especially in long methods.
Object get(int index, Object defaultValue) {
undef index, defaultValue;
return "constant default value";
}
This would also serve as a documentation that the programmer thought about these otherwise unused parameters.
I don't think there is such a thing as undeclaring objects i .Net. If your object uses resources that needs to be cleaned up it should implement the IDisposable interface. Otherwise the garbage collector will take care of everything.
精彩评论