Home > Net >  classes that can only be instantiated with the using keyword
classes that can only be instantiated with the using keyword

Time:10-23

I'm new to C# and .Net platforms. I have a problem.

I want to create a custom class. This class has Disposible method and implements the IDisposible interface. And I want to if everyone want to using my class and create instance he must to use using syntax.

Because I want to it

using (Person person = new Person()) 
{
    // Some code example
};

I don't want to use create a instance without using declarations

Person person = new Person () // I don't want it this method

Is it possible or not? (maybe a custom attribute, maybe .net attributes, maybe another method)

What do you? What advice would you give me about this job?

CodePudding user response:

It's perfectly possible that you want to delay calling Dispose beyond a using statement:

void Func()
{
   var thingToDispose = new DisposableThing();
   DisposeMyThing(thingToDispose)
}

void DisposeMyThing(IDisposable disposable)
{
   disposable.Dispose();
}

Therefore you cannot do this with just implementing IDisposable.

I believe your original requirement is not possible.

CodePudding user response:

I think there is one reason why this will never be supported in C#:

In other words: it must be supported that an instance can be created in a different scope than where it is used. It would already be impoosible to use factory methods like:

using var p = GetPerson(); // different scope
// ...
  • Related