Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Since ref struct is stack-only, it could have a destructor, which would be executed when the struct goes out of scope. If I write a function library for others, although I provide dispose function, users can still ignore it and forget to release resources. I can't force them to use "using". But if ref struct supports destructor, I can use it to wrap my functions to ensure releasing resources. #7029

Closed
SamiG42 opened this issue Mar 4, 2023 · 0 comments

Comments

@SamiG42
Copy link

SamiG42 commented Mar 4, 2023

    Since ref struct is stack-only, it could have a destructor, which would be executed when the struct goes out of scope. If I write a function library for others, although I provide dispose function, users can still ignore it and forget to release resources. I can't force them to use "using". But if ref struct supports destructor, I can use it to wrap my functions to ensure releasing resources.

For example:

ref struct A
{
    FileStream file;
    public A(string filename)
    {
        file = new FileStream(filename, FileMode.Open);
    }
    ......  //other member functions
    ~A() //destructor 
    {
        if(file)
        {
           file.Close();
           file=null;
        }
    }
}

static void test()
{
    A a=new A("D:\test.txt");
    ......
} //destructor of "a" would be executed here automatically

related issue: #231


Add a rule: ref struct with destructor can't assign each other.

Originally posted by @ygc369 in #1110

@SamiG42 SamiG42 closed this as completed Mar 4, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant