Click here to Skip to main content
15,887,083 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
This is not a problem just a question about the using statement.
If I have a routine like this.
public static int UpdateSeries(int mazeSeriesID)
		{
			Gbl.z_MethodMain = "(Common)UpdateShows";

			using SqliteDBContext dbContext = new();

have some code which updates or creates sqlite records then executes a save changes block as follows.

}

public static bool SaveEntityChanges(string label = "")
		{
			Gbl.z_MethodMain = "(Common)SaveEntityChanges";
			bool result = true;

			try
			{
				DbContext.SaveChanges();
			} catch(Exception ex)
			{
				Utils.WriteLog(
					Gbl.z_MsgLogName,
					1,
					"Error occurred while Saving Changes to Database - Exception= " + ex.Message,
					Gbl.z_MethodMain,
					label);
				result = false;
			}
			return result;
		}


Does the using statement persist over the executed save changes routine?
Does it persist over other routines executed from within the block?
Will the using only end on a return?
What is the difference if I put all the code within braces?

I am new to this all the doco does not make it clear.

What I have tried:

I have currently only tried doing this within a block.
Posted

There are two different forms of using*
The using statement which requires parentheses:
C#
using (MyClass mc = new MyClass())
   {
   // mc in scope here
   ...
   }
// mc no longer in scope
The system will automatically call Dispose for the variable when the block of code is exited in any way: fall through, exception, break, continue, throw, or return.

The using declaration:
C#
   {
   ...
   using MyClass mc = new MyClass();
   // mc in scope here
   ...
   }
// mc out of scope here
The variable will be Disposed when the code exits the scope in which the variable is declared (he enclosing curly brackets, usually) in the same way as for the using statement.


* Well, three - there is also the using directive which appear at the top of the file and creates aliases.
 
Share this answer
 
See for some good understanding with examples C# Using (How It Works For Developers) | IronPDF[^]
 
Share this answer
 
Comments
Graeme_Grant 7-Jan-24 19:56pm    
This answer appears to be commercial and spam in nature.
M Imran Ansari 8-Jan-24 4:51am    
How?
M Imran Ansari 8-Jan-24 4:54am    
We only concern about the article contents instead of any other services. I don't think If the contents are self explanatory with good examples we shouldn't consider it.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900