Using statement best practice [closed] - c#

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
It may be a silly question, but since I can't give it an answer by my own, I will ask it here.
Let we have a module that we want to use in an http handler (the web app is written in C# using ASP.NET) and let that this module implements the IDisposable interface. Then a common approach is to
use the module as below:
using(var module = new ModuleName(param1, param2, param3))
{
}
Is it better to place any code to variables that we are going to use only inside the body of this using statement or before this. In terms of code:
Is it better (and why) the first approach or the second approach:
first approach
using(var module = new ModuleName(param1, param2, param3))
{
int a = Request.GetParam<int>("aNumber");
string b = Request.GetParam<string>("bString");
// and other parameters contained to the http request
}
second approach
int a = Request.GetParam<int>("aNumber");
string b = Request.GetParam<string>("bString");
// and other parameters contained to the http request
using(var module = new ModuleName(param1, param2, param3))
{
}
If there isn't any technical reason -and it is an opinion based decision- that we should prefer the first approach to second approach or vice versa, please let me know, in order to delete my post.

It depends on if you need those variables outside of the scope of the using-statement. If so, you need to declare them outside anyway. If not, declare them in the using.
Why? It's all about readability, fail-safety and refactoring.
This is true not only for the using but scopes and variable declaration in general. Read:
https://codereview.stackexchange.com/questions/6283/variable-declaration-closer-to-usage-vs-declaring-at-the-top-of-method
https://softwareengineering.stackexchange.com/questions/56585/where-do-you-declare-variables-the-top-of-a-method-or-when-you-need-them

Related

Apply get set for methods? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I have just learned get set principles in C# and I wonder whether there is any interest of using the same principle for methods.
If I understand well, get and set are used for variables. But it could be possible to apply the same principle for methods. For instance:
private int _GiveMultiply()
{
int a = ...
int b = ...
return c = a*b;
}
public int GiveMultiply
{
get { return _GiveMultiply(); }
}
But is there any kind of interest to do such a thing ?
For example is there a risk to use a public function that can be prevented using such a process ?
The answer is: it depends. I'll try to help you to reformulate your question: does it make any sense to return a function rather than computed result from another fuction? Then I would say: definitely yes (let me know if you'd like to know ehy, I'll update this post). But the example you showed does not return a fuction, it just wraps it into yet another fuction, which is useless. The only exception is various kinds of abstract method patterns, where you might have public function with some predefined logic and call to the abstract/virtual fuctions; rarely they do have same name, then indeed wrapping sort of works.

Is it good idea to have a general try/catch in every method in a controller or is there a better way? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
I'm trying to improve my MVC.NET Core-fu and I ended up in a bunch of methods in all my controllers looking like this (note the outermost, general, repetitive try-catch).
[HttpPost]
public IActionResult DoSomething([FromBody] Thing thing)
{
try
{
if (...)
return Ok(thing);
else
return NotFound();
}
catch (Exception) { return BadRequest(); }
}
The way I see, I want to have the baddy-requesty just in case. Now, that adds a lot of code to otherwise rather simple controller and I have a suspicion that someone before has thought of this and proposed a solution.
I haven't found such thing (and I was informed that filters are obsolete for usage in Core). Possibly it's because I'm not familiar with the right search keys.
This seems excessive to me. Many methods won't execute instructions that are likely to fail. For those extremely rare cases, a global error handler would be more than sufficient.
For those methods that access the disk, a database, or perform calculations that could raise exceptions (something you should probably be avoiding in the first place), a try...catch block makes sense.
But even in these cases, if a method with a try...catch handler calls another method, there is no reason to put handlers in that other method.

Create new object best practices [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
There are times I instantiate a new object within a method call for sake of streamlining code instead of assigning the new object to a variable. What drawbacks exist in doing one or the other?
T myobj = new T();
elements.Add(myobj);
--vs--
elements.Add(new T());
Need a reference later
As adaam mentioned in the comments, if you need to keep a reference to an object because you'll be using it, then it's better to do it this way.
T myobj = new T();
elements.Add(myobj);
T.DoStuff(); //this might need to happen further down in the code, so keeping the reference is handy. Otherwise we'd have to dig it out of the elements. And you might be thinking "well, I don't need to reference it later in the code." But what if you're refactoring the code and it requires some modification? Now you'll need to change it, rather than having done it with a separate declaration in the first place.
Debugging
A common situation is when you're stepping through code with the debugger. It's difficult to see properties of an object that was created in this manner.
elements.Add(new T());
When given its own reference, you can easily use your IDE's debugging tools to check the values if the code is written like this:
T myobj = new T();
elements.Add(myobj);
Readability
Another reason to choose one over the other would be readability. That one is opinion based, but you should ask the team you're working with which is more readable in order to determine which practice to follow. Asking everyone on Stack Overflow which reads better is off topic.

How is "using" statement supposed to work? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm trying to take advantage of the using statement in the following code:
Uri uri = new Uri("http://localhost:50222/odata");
var container = new CourseServiceRef.Container(uri);
CourseServiceRef.NotNeeded newTempUser = new CourseServiceRef.NotNeeded()
{
Email = model.UserName,
Username1 = model.UserName
};
container.AddToNotNeededs(newTempUser);
container.SaveChanges();
However this doesn't compile. Why?
using statement - not to be mingled with using directive - is meant for objects that implement the IDisposable interface so that they're disposed of automatically at the end of the code block:
using (var toto = new MyDisposableClass())
{
// do stuff
}
If any of your classes do implement this interface (or inherit from something that does), you may use the above syntax to ensure call to Dispose() method. You cannot use using blocks for objects that does not implement this interface, it simply won't compile.
Essentially, this will be doing the same as the following:
var toto = new MyDisposableClass()
try
{
// do stuff
}
finally
{
if (toto != null) ((IDisposable)toto).Dispose();
}
The only difference here would be that in the first scenario, toto's scope dies at the end of the using block.
The purpose of "using" is to ensure Dispose() is called on an object that implements IDisposable. Therefore, the best way to use using keyword in your code is, like in any other code, on objects that implement IDisposable. This could be, for example, your "newTempUser" or your "container". Since we do not have access to their definitions, only you can answer this question.
There aren't really good and bad uses of using. Either you use it or you don't. If you don't use it when instantiating a class implementing IDisposable then you've likely made a mistake (unless you have some good reason for calling Dispose yourself elsewhere which is a very small percent of use cases).
If you fail to use it then the point when the resource is disposed of is less predictable and it will likely have negative effects on your applications performance. There aren't different ways of using it, there is only one;
using (ClassImplementigIDisposable instance = new ClassImplementigIDisposable())
{
// code that uses instance
// at the end of this block `Dispose` will be called on instance
}

Best way to store bunch of constant values in .NET [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
This is basically a a design question:
I am rewriting an application in C# which is basically written in C++. C++ has this nice concept of Header files which will gold a lot of declared constant values for the consuming file.
However, we do not have Header files in C#. I may have two options
Create a class which will hold a lot of constant values for me(No so standard)
Store values in XML (Standard-But involves a lot of parsing hassle)
Which is a better solution? Is there any other solution that I may not know of?
Personally i'd use a static class and place all the values in there.
public static class Constants
{
public const int Ten = 10;
public const int Twenty = 20;
....
}
EDIT
As #JonSkeet suggested, it's better if you store these values in classes they pertain to, however, that might not always be possible.

Categories

Resources