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
}
Related
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 9 months ago.
Improve this question
I'm in a situation where I have to new up a ViewModel that has an event and based on the view chosen by the user I might need to swap back and forth between this one and other ViewModels with the same interface, every time they have to get the updated data.
These ViewModel contains a list of ViewModels that I need to display.
Is it ok to do detach and attach to the event this way outside the usual Dispose method?
if (_animalsListVm is not null)
{
_animalsListVm.MyEvent -= Handle_MyEvent;
}
_animalsListVm = MakeListViewModel();
_animalsListVm.MyEvent += Handle_MyEvent;
await _animalsListVm.InitializeAsync();
Granted this code might be messy, I'm using Blazor and I was trying to find an alternative to have enums or booleans to show a component, so I decided to switch view based on the concrete type of the current ViewModel.
Attaching and detaching events outside dispose methods is generally fine.
In some cases a pattern like this might be preferable:
public IDisposable RegisterForEvent(Action<EventArguments> eventHandler);
This follows the typical dispose pattern. This pattern might be preferable if you need to do some work when registering or unregistering events. You could do the same with a regular event, but I would typically not expect an event registration to do any time consuming work.
I am however not a fan of initialization methods. While they can be hard to avoid, I prefer objects that are completely constructed when the constructor returns, perhaps something like:
_animalsListVm?.Dispose();
_animalsListVm = await MakeListViewModel(Handle_MyEvent);
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 6 years ago.
Improve this question
The function of [Obsolete] is essentially to stop a class/function from being used but still to maintain it in code for the record.
Is there any good reason why [Obsolete] should be used as opposed to just deleting, or commenting out the code. This question is even more relevant if you have source control so there is no point keeping the code for reference purposes as it will be in the SC.
I'm curious as to what is considered best practice?
It is used mostly for backwards compatibility, so when you do a new implementation of a functionality that has a different expected behaviour, any code using the old functionality will still work, but you make sure that new uses of your library uses the new implementation.
If you are maintaining a library that is being used by third parties, you should develop a road map of when and if the obsolete functionality is going to be removed. The if it's important, because many times you are just indicating that that function is no longer to be maintained and the new one should be used instead.
Internally, it can be used in refactors to replace poorly-implemented-but-working functionality in a gradual way. You mark it as obsolete and start working through the warnings until you see no more of them, then you can proceed to safely remove it.
Be aware that this is an opinion based on experience on renewing legacy code bases and there is no common consensus.
The Obsolete attribute marks a program entity as one that is no longer recommended for use. Each use of an entity marked obsolete will subsequently generate a warning or an error, depending on how the attribute is configured.
Here an example for Hashtable comparer from reference source.
[Obsolete("Please use KeyComparer properties.")]
protected IComparer comparer
{
get
{
if( _keycomparer is CompatibleComparer) {
return ((CompatibleComparer)_keycomparer).Comparer;
}
else if( _keycomparer == null) {
return null;
}
else {
throw new ArgumentException(Environment.GetResourceString("Arg_CannotMixComparisonInfrastructure"));
}
}
set
{
if (_keycomparer is CompatibleComparer) {
CompatibleComparer keyComparer = (CompatibleComparer)_keycomparer;
_keycomparer = new CompatibleComparer(value, keyComparer.HashCodeProvider);
}
else if( _keycomparer == null) {
_keycomparer = new CompatibleComparer(value, (IHashCodeProvider)null);
}
else {
throw new ArgumentException(Environment.GetResourceString("Arg_CannotMixComparisonInfrastructure"));
}
}
}
The documentation for the ObsoleteAttribute describes it's reasons for existence fairly well...
Marking an element as obsolete informs users that the element will be removed in future versions of the product.
As mentioned in the comments, this is obviously only really useful if others are using versions of your assembly.
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
I'm working on a simple repository class on top of a ADO.NET SQL connection. The class is sealed and implements the IDisposable pattern.
I intended to keep it simple so I open the SQL connection in the constructor and closed through the Dispose() method so it can be used with the using statment.
using (var r = new MyRepository(connectionString))
{
...
}
I originally had a pair of Open/Close method for this class but I found it makes the class much harder to implement and also more confusing to use.
Do you typically have Open/Close methods for your repository class? If so why?
MSDN Dispose Pattern guideline says:
CONSIDER providing method Close(), in addition to the Dispose(), if
close is standard terminology in the area. When doing so, it is
important that you make the Close implementation identical to Dispose
and consider implementing the IDisposable.Dispose method explicitly
So, taking into account that open-close terminology is often used in database interactions, your idea to have them is good and quite viable.
But, if their implementation and use makes your classes much more complex to no or minimal advantages then do not create them. In the end you always know your system and requirements better, so you should base your decisions on your concrete situation, not on abstract guidelines and principles.
P.S.: Whether you have these methods or not, your system should open connections for smallest possible amount of time and close them as soon as they are no longer needed. And it is often difficult to accomplish when you have to put some special disposal code in the end of each use.
I suggest not implementing IDisposable directly on your repository class.
Instead, obtain and release resources as necessary within each method of the repository.
public class MyRepostory : IRepository
{
public IEnumerable<Foo> GetFoos()
{
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
// ... get the data, etc. ...
return foos;
}
}
}
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
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.