Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Managed C++ equivalent to the C# using statement

Tags:

How would one code the following C# code in Managed C++

void Foo() {     using (SqlConnection con = new SqlConnection("connectionStringGoesHere"))     {          //do stuff     } } 

Clarificaton: For managed objects.

like image 519
Adam Tegen Avatar asked Dec 03 '08 22:12

Adam Tegen


People also ask

What does the caret mean in C?

Arithmetic Operators Note: Origin C, by default, treats the caret character (^) as an exponentiate operator . This is done to be consistent with LabTalk. ANSI C uses the caret character as the exclusive OR operator.

What is managed C++ code?

Managed C++ is a language invented by Microsoft, that compiles to bytecode run by the . NET Framework. It uses mostly the same syntax as C++ (hence the name) but is compiled in the same way as C# or VB.NET; basically only the syntax changes, e.g. using '->' to point to a member of an object (instead of '.

What does the Carat mean in C++?

From MSDN, it looks like the caret means you are getting a handle to the type being created.


1 Answers

Assuming you mean C++/CLI (not the old Managed C++), the following are your options:

(1) Mimic a using-Block with using automatic / stackbased objects:

{   SqlConnection conn(connectionString); } 

This will call the Destructor of the "conn" Object when the next enclosing block ends. Whether this is the enclosing function, or a block you manually add to limit scope doesn't matter.

(2) Explicitly call "Dispose", i.e. destruct the object:

SqlConnection^ conn = nullptr; try {   conn = gcnew SqlConnection(conntectionString);  } finally {   if (conn != nullptr)     delete conn; } 

The first one would be the direct replacement for "using". The second one is an option, typically you won't need to do unless you optionally pass the reference to somewhere else.

like image 133
Christian.K Avatar answered Oct 21 '22 12:10

Christian.K