0

Trying to learn using statement. How to call add function of newly created unnamed object in tst() function:

public class AnswerCmd : IDisposable
{

    public static void tst()
    {
        using (new AnswerCmd())
        {
            //add(5); not works
        }

    }



    public void add(int value)
    {
        //....
    }

    public void Dispose()
    {
        throw new NotImplementedException();
    }

}
Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
vico
  • 17,051
  • 45
  • 159
  • 315

3 Answers3

4

Because the add is not static, you need to create a new instance of AnswerCmd to access it, like this:

using (var instance = new AnswerCmd())
{
    instance.add(5);
}
Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
0

Because tst function is a static function, but add functuon isn't.

If you want to create an instance try to remove static

public class AnswerCmd : IDisposable
{

    public void add(int value)
    {

    }

    public void Dispose()
    {

    }

}

then you can use like this in outside

using (var ans = new AnswerCmd())
{
    ans.add(5);
}

Note

remove throw new NotImplementedException(); in Dispose function otherwise, you will get the error when your leave the using.

D-Shih
  • 44,943
  • 6
  • 31
  • 51
0

Your code is almost Ok but if you change your code a little more you can do what you want. This is your code with a little change:

public class AnswerCmd : IDisposable
{
    public static void tst()
    {
        using (AnswerCmd var = new AnswerCmd())
        {
            var.add(5);
        }
    }

    public void add(int value)
    {
        Console.WriteLine($"Add: {value}");
    }

    public void Dispose()
    {
        //throw new NotImplementedException();
    }
}

You must declare a variable AnswerCmd var in your using statement in type of your class and then after creating and assigning and object to it like this AnswerCmd var = new AnswerCmd() call your add method like this var.add().

If you want to know more about that and why you should do that, I have to say this is because your tst method is static and your add method is non-static. non-static methods are just for objects of your class and you cannot call them when you don’t created an object from that class. When you call a non-static method directly without creating an object this is a syntactic error.

You also must remove or comment throw new NotImplementedException(); in Dispose method because, your method will throw and Exception when you leave the using.

This is good if you visit this link and read more about differences between static and non-static methods.