classes that can only be instantiated with the using keyword

Berkay Akar 26 Reputation points
2022-10-21T11:23:52.29+00:00

Hi dear form users

I have a question. ı want to make a create instanse of my costumized class but I want this action to be real using only the word "using". compiler to remind when "using" key is not used. and program get exception .

public class Deneme   
{  
    public int ID  { get; set; }  
    public int Name { get; set; }  
    public int Surname { get; set; }  

}  
 

    static void Main()  
    {  
        using (Deneme d = new Deneme()) // My costume class using only this method   
        {  
            // Operation  
        }  
    }  



 static void Main()  
    {  
        Deneme d = new Deneme(); // Compiler get an error when didnt used using keyword   
    }  

I don't want you to get an example without using the using keyword

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,924 questions
{count} votes

3 answers

Sort by: Most helpful
  1. Olaf Helper 44,501 Reputation points
    2022-10-21T11:33:16.31+00:00

    Keyword "using" can only be used with classes implementing IDisposable Interface; your class don't.

    compiler to remind when "using" key is not used. and program get exception .

    That's not possible.


  2. AgaveJoe 28,371 Reputation points
    2022-10-21T13:14:58.717+00:00

    I believe the compiler error is telling you that it cannot find the Deneme class and is asking if you need to make a reference or add a using statement with the namespace of the type to the top of the code file. Visual Studio shows a help icon that lists possible code fixes for the this fundamental programming construct.

    For example.

    using Namespace.Deneme;  
    

    https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/namespace

    0 comments No comments

  3. Viorel 117.3K Reputation points
    2022-10-21T14:43:00.13+00:00

    Check a different approach:

    static void Main()  
    {  
        MyClass.PerformOperation(some parameters);  
    }  
    

    where PerformOperation is a static function of static class. Inside this function you can use your disposable internal classes and the using statement. You and other people that call this function will not have to remember to use using.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.