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.