Questions tagged [using-statement]
A `using` statement is a C# and VB.NET language feature that simplifies deterministic cleanup of disposable resources. Not to be confused with the (C# only) `using` directive (related to namespaces), for which use tag `using-directives`.
436
questions
0
votes
2
answers
46
views
C# What is the point of the using statement? [duplicate]
I'm not talking about references to assemblies, rather the using statement within the code.
For example what is the difference between this:
using (DataReader dr = .... )
{
...stuff involving data ...
1
vote
1
answer
58
views
Why exiting "using" invokes unexpected Dispose()?
Here is my case:
class A : IDisposable
{
public void Dispose() { Console.WriteLine("A Dispose"); }
}
class B : A
{
public new void Dispose(){ Console.WriteLine("B Dispose")...
1
vote
1
answer
134
views
Why is c# creating a file before any file stream is created?
Background:
I am creating an avaloniaUI project and in it I have a json config with a class that serializes and deserializes it on initialization and editing. If the file can't be found on ...
1
vote
1
answer
64
views
using statement for multiple assignments to the variable
I have a variable "pen" of type System.Drawing.Pen which is getting assigned multiple times in a particular method. I want to put it within "using" statement. How I can do that?
...
0
votes
1
answer
88
views
Syntax for using declaration without variable
Consider a disposable with side effects in the constructor:
public class MyDisposable : IDisposable
{
public MyDisposable()
{
// Some side effects
...
}
public void ...
2
votes
1
answer
140
views
Invoke a Method of Child form opened with Using Statement
I am trying to figure out how to invoke a method of a child form which is opened in a using block.
In my code, I have a MainForm which is a MDI parent. MDI parent holds a reference of parent form . A ...
0
votes
0
answers
56
views
Εrror when locking a local variable: "Possibly incorrect assignment to local which is the argument to a using or lock statement."
I have an in memory static repository which is used both for writing into it and reading from it. When writing (updating) that repository, I would like to make it completely exclusively available for ...
0
votes
1
answer
52
views
Type used in a using statement should be implicitly convertible to IDisposable
I have the following logic:
try
{
using (var contents = new StreamReader(file.InputStream).ReadToEnd())
{
var rows = contents.Split(new[] { Environment.NewLine }, StringSplitOptions.None)...
0
votes
0
answers
32
views
Using same disposable object twice in diffrent using-statment [duplicate]
I have made a disposable class UnitOfWOrk which will also acts as an optional parameter, I have provided an exampel below.
public async Task CallPersistItemPassUoW()
{
using (var unitOfWork = new ...
0
votes
1
answer
24
views
Using block - scope issues
I am learning visual basic and OOP on the fly.
This piece of code displays the query results to a combo box on a form...
Dim c = System.Configuration.ConfigurationManager.ConnectionStrings("db&...
0
votes
1
answer
119
views
Why is the using variable disposing itself before leaving the method?
using PuppeteerSharp;
using System;
using System.Threading.Tasks;
namespace Video_Handler
{
public class VideoHost
{
private static bool Is_HTTPS_URL(string url)
{
...
0
votes
2
answers
569
views
Is my way of using MongoDB C# driver FindAsync flawed?
Still kind of new to C#. My code gives me the results I want, but I'm uncertain if I did implemented it in an OK way. Please elaborate if you feel like answering.
My goal was to search for entries in ...
5
votes
1
answer
371
views
Why can't a using variable be used within a switch section without braces in C#?
Consider the following code:
switch ("")
{
case "":
using var s = new MemoryStream();
break;
}
The above code won't compile with this ...
3
votes
1
answer
5k
views
Auto import usings not working Visual Studio 2019
I have the following selective problem with VS 2019 and IntelliSense.
When I start typing a class name which's namespace is not imported yet, IntelliSense suggests it in the Autocomplete column.
Once ...
2
votes
1
answer
73
views
Do I need to release a connection if I throw an error?
So if I get a connection pool, then something unexpected happens and the error will be thrown, do I need to additionally release a connection? What happens with the MySQL connection pool once the ...
-3
votes
2
answers
96
views
'Using static' on a class contained private enum in C# [duplicate]
Consider the following
class Body
{
[Flags]
enum Organs { None = 0, Brain = 1, Heart = 2, Kidney = 4, Skin = 8 }
Organs damagedOrgan = Organs.Heart;
Organs currentOrgan = Organs....
0
votes
1
answer
250
views
How can I fix the error on Newtonsoft.Json using statement?
I am working on a .Net console app with c# and I have just added the Newtonsoft.Json using statement but VS code points it out as an error
The type or namespace name 'Newtonsoft' could not be found (...
0
votes
0
answers
831
views
Auto Importing Using Statements in VS Code
In Visual Studio, when you see a red line, you can place your cursor over the word, press Ctrl + . and click on the namespace you want to import (via a using statement). Is there a way to do this in ...
0
votes
1
answer
76
views
IDisposable, using and GarbageColleciton [duplicate]
I got stuck in the weeds of how IDisposable and the GarbageCollector work.
Suppose you have an IDisposable object, which doesn't actually have an resources that it's holding onto (but the Dispose() ...
0
votes
0
answers
85
views
Does c# uses IDisposable / Dispose for temporary COM objects?
To make sure that a COM object that I need to create is freed/released as soon I didn't need it anymore is simple with the using statement.
using (dynamic a = new MyFooCOMApplication())
{
...
}
...
0
votes
1
answer
138
views
Declare a resource outside the using statement
I have a question about C# using statement. According to the docs, it is a best practice to both declare and initialize the resource (for instance, a SqlConnection object) inside the using statement. ...
0
votes
0
answers
106
views
CS0103 in vstudio debug mode says things don't exist
In Debug Mode, with using static XXX.YYY; in place:
My c# code works fine. But when stepping through my code in debug mode I noticed several places where the debugger says "CS0103 The name NAME does ...
2
votes
2
answers
100
views
C# - Is there a reason NOT to instantiate a class and use it in a single line of code?
I know this would be a correct way to use a StreamWriter:
using (StreamWriter sw = new StreamWriter(hreq.GetRequestStream()))
sw.Write(jsonPostData);
But what about this? Is this also valid or ...
0
votes
0
answers
96
views
Are there guarantees in C# that the using statement won`t inherit the try + finally combinations issues? [duplicate]
Are there guarantees in C# that the using statement won`t inherit the try + finally combinations issues?
The question naturally follows the discussion from other here.
According to the documentation:...
0
votes
0
answers
56
views
C# Get classes that has a reference to a specific type
In my project I would like to know the references of a specific type within my C# project. For example I have the class EntityA.
I have two other classes ProcessA and ProcessB. ProcessA and ProcessB ...
1
vote
2
answers
286
views
Does it make sense to have using statement inside class constructor? [duplicate]
I mean using the statement below, inside the constructor of my class I use FileSystemWatcher instance, does it make sense to have using statement inside class constructor like this or it must be ...
8
votes
3
answers
427
views
Refactoring: using statement without scope, when does the implicit `Dispose` call happen?
I was refactoring some the other day, I bumped into something like that:
public async Task<Result> Handle(CancelInitiatedCashoutCommand command, CancellationToken cancellationToken)
{
using ...
0
votes
1
answer
45
views
Why does _session.Use method not work properly?
I have a job like this:
[UnitOfWork]
public override void Execute(CompleteIRHJobArgs args)
{
var robotUserId = _userRepo.GetAll().Where(p => p.UserName == TestaLIMSWPConsts.LIMSRobot).Select(p ...
0
votes
0
answers
38
views
Invalid attempt to call FieldCount when reader is closed occurring after fix put in for connection pool issue
The site I maintain was built with ASP Webforms. I was not involved in building it. Since upgrading the server where it is hosted we started seeing a lot of the following error:
"Timeout expired. The ...
1
vote
3
answers
248
views
'using' keyword vs class field for Entity Framework
I know the using keyword basically calls Dispose() after scope ends, however, is it bad practice or unacceptable to have the variable from the using clause be a class field? Example:
public class ...
-3
votes
2
answers
183
views
C# Dispose resources on exceptions without using
I'm writing a class library which includes socket operations. I don't want to rely on the consumer to dispose resources after finishing or when an exception is thrown.
Normally I would use the "using"...
1
vote
2
answers
354
views
How the MemoryStream declared in outer using statement is still available after inner using statement closes?
The Microsoft docs have the following piece of code on this page:
https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography.cryptostream?view=netframework-4.7
The most inner 'using' ...
0
votes
2
answers
266
views
Multiple using statements with if condition
I need to read one file and write processed data into one or optionally two files.
How to organize the Using statements in this case?
Will something like this work?
if (condition)
using (var sw2 ...
4
votes
2
answers
126
views
Can I safely use object initializers inside using statements?
I'm wondering if the use of object initializers inside using statements somehow prevents the correct disposal of the resource declared inside them, e.g.
using (Disposable resource = new Disposable() {...
2
votes
1
answer
45
views
Multiple using declarations throw 'IOException' but statements don't when writing files
using declarations were just introduced in C# 8.0 but they don't behave the same as using blocks, or so i think.
The following nested using block works fine:
using (var resource = Assembly....
0
votes
2
answers
198
views
Including other files in Unity without the "using" statement
I have to integrate someone's code from a Unity project.
They created a file with the definition of a class that's an array of points, and another file that uses the first file's class.
Problem: I don'...
4
votes
3
answers
109
views
Is it good practice to use "using" on a new empty DataTable?
I've been rewriting some old code so that the using statement is used for my DataTables, instead of remembering to Dispose each time:
using (DataTable dt = BLL.GetDataTable()) {
foreach(DataRow dr ...
-1
votes
1
answer
351
views
Try/Catch with an SQL connection [duplicate]
This is a follow up question to this question:
Correct use of Try Catch for the SQL connection in C#
when you write a code like:
using (SqlConnection connection = new SqlConnection(connectionString)...
-3
votes
2
answers
85
views
Any way to have a `using` block that doesn't define a scope block?
using(var myDisposable = new MyDisposable)
{
//Do stuff.
}
is great and all.
But if what you wanted was:
using(var myDisposable = new MyDisposable)
{
var myAnswer = CalculateMyAnswer(...
0
votes
0
answers
583
views
.net memory leaking with Thread.Abort() and using statement
Edit:I am trying to use Constrained Execution Regions as a new weapon against Abort(). I am still running test, I hope it work. Abort() is really a bad thing. I will report later.. If anyone has any ...
1
vote
1
answer
101
views
Using Statement Connection not closed exception
How do I stop ASP.NET, C# class functions throwing Connection not closed exception before the using statement instantiates the connection? This is happening when debugging in Visual Studio 2019 ...
3
votes
2
answers
236
views
How to use the 'using' command properly?
I just created this account so please forgive me if I forgot some crucial information.
I have the following code but I suspect that there is a memory leak. The goal of the code is to get the bytes ...
0
votes
0
answers
19
views
Is there any way to use the same shortcut for two commands in visual studio 2015?
I'm using Visual Studio 2015 and I want to press (Ctrl + K, Ctrl + D) and, then have my code formated and using directives sorted and remove unsued ones.
In summary, Pressing (Ctrl + K, Ctrl + D) ...
2
votes
3
answers
130
views
Object in Using Statement Is NOT Immutable?
In some legacy projects at my work, I see a lot of using statements referring to the dbContext:
using (myContext dal = new myContext())
{
dal.DoSomeDatabaseThing
}
I believe this is fairly ...
-2
votes
2
answers
87
views
Will I still get the Dispose advanges, if I in a using, initialize with null?
I would like to refactor my SqlDataReader code, so it's using using..
SqlDataReader reader = null;
reader = xdCmd.ExecuteReader();
// use reader..
Can I use solution 1) where I declare the reader in ...
0
votes
1
answer
5k
views
C# TcpClient and NetworkStream to send/receive data over TCP. Why not using "using" block and can I read data right after writing it to stream?
I am reading documentation on using TcpClient and NetworkStream to write and read from a Tcp connection stream. But I notice that all Microsoft's documentation is not using "using" block even thought ...
3
votes
1
answer
2k
views
"Access to disposed closure" warning in using statement
I am using a "using statement" to ensure a StreamWriter is being cleaned up properly.
using (StreamWriter fout = new StreamWriter(tempFile))
{
data.ForEach(line => fout?.WriteLine(line));
}
I ...
0
votes
3
answers
144
views
Call function of unnamed object in using statement
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 (...
1
vote
2
answers
368
views
IF condition check inside USING method and SqlConnection
I am trying to run data validation, execute some code and pass data from one SQL query to another.
My current code looks like the below:
public string SelectUniqueKeyNumber()
{
string newList = ...
2
votes
3
answers
112
views
Stacked using statements vs seperate using statements
While refactoring code I stumbled upon some stacked using statements (I'm talking about 10 to 15-ish).
using(X x=new X())
using(Y y=new Y())
using(Z z=new Z())
using(...)
{
List<X> listX= x....