C
codymanix
Last night I had several thought about RAII and want to discuss a bit.
Why doesn't CSharp support destructors in structs? Wouldn't that make RAII
possible like in C++? When the struct goes out of scope, the dtor could be
immediately be called (no GC needed).
For that, you don't have to declare the whole File class as a struct (which
would be not good for performance when File has a lot of data-members).
Instead creating a thin wrapper would be a good solution:
public struct MyFile
{
File f;
public MyFile(string p) { f=new File(p); }
~MyFile() { f.Close(); }
}
That would do it.
I have a second though which got through my mind. What about introducing an
interface which is recognized by the compiler and forces usage of the
using() statement.
public interface IDisposableForce : IDisposable{}
A second possibility could be declaring an attribute which marks
IDisposable-implementing-classes wheather using() should be mandatory or at
least suggested.
enum WarnLevel {NoWarn,WarnLvl1,WarnLvl2,WarnLvl3,WarnLvl4,GenerateError};
class UsingAttribute{UsingAttribute(WarnLevel w){}}
[Using(WarnLvl3)] // that means if warnlevel 3 or higher is set a warning
is issued when this class is used without using()-statement
public class MyFile : File
{
public class MyFile(string p) :base(p){}
}
What do you think?
Why doesn't CSharp support destructors in structs? Wouldn't that make RAII
possible like in C++? When the struct goes out of scope, the dtor could be
immediately be called (no GC needed).
For that, you don't have to declare the whole File class as a struct (which
would be not good for performance when File has a lot of data-members).
Instead creating a thin wrapper would be a good solution:
public struct MyFile
{
File f;
public MyFile(string p) { f=new File(p); }
~MyFile() { f.Close(); }
}
That would do it.
I have a second though which got through my mind. What about introducing an
interface which is recognized by the compiler and forces usage of the
using() statement.
public interface IDisposableForce : IDisposable{}
A second possibility could be declaring an attribute which marks
IDisposable-implementing-classes wheather using() should be mandatory or at
least suggested.
enum WarnLevel {NoWarn,WarnLvl1,WarnLvl2,WarnLvl3,WarnLvl4,GenerateError};
class UsingAttribute{UsingAttribute(WarnLevel w){}}
[Using(WarnLvl3)] // that means if warnlevel 3 or higher is set a warning
is issued when this class is used without using()-statement
public class MyFile : File
{
public class MyFile(string p) :base(p){}
}
What do you think?