Can ReSharper live templates do conditional code generation? - resharper

Example: I would like to have a template that inserts a method. If the class is declared sealed, then I'd like the method to be declared private. If the class is not sealed, then I'd like the method to be declared protected virtual.
Another example. If the class is inherited, and the superclass contains a method X, then call base.X(); otherwise do nothing.
Is this type of conditional processing available in ReSharper? I guess this is getting close to T4 territory but it would be really handy to be able to do this in Live Templates.
In case it matters, I'm using R# 7.
Detailed scenario
Both of these requirements came from trying to write a Live Template for the IDisposable pattern (see Implementing the Disposable Pattern Correctly). The generated code needs to be different depending on whether the class is a base class or subclass. One can define two templates, but it is not difficult to dream up other scenarios where this would be useful. Here's the code in my IDisposable template:
#region IDisposable Pattern
/// <summary>
/// Finalizes this instance (called prior to garbage collection by the CLR)
/// </summary>
~$ClassName$() {
Dispose(fromUserCode: false);
}
public void Dispose()
{
Dispose(fromUserCode: true);
GC.SuppressFinalize(this);
}
private bool disposed = false;
// Declare as private if this class is sealed.
protected virtual void Dispose(bool fromUserCode)
{
if (!disposed)
{
if (fromUserCode)
{
// ToDo - Dispose managed resources (call Dispose() on any owned objects).
// Do not dispose of any objects that may be referenced elsewhere.
}
// ToDo - Release unmanaged resources here, if necessary.
}
disposed = true;
// ToDo: Call the base class's Dispose(Boolean) method, if available.
// base.Dispose(fromUserCode);
}
#endregion

You can certainly do this. What you need is a plugin that implements the corresponding live template macro that performs the actual check.

Related

Does Dart/Flutter have the concept of weak references?

I'm in the early stages of learning Dart & Flutter. I'm looking at how to implement an eventbus, which works fine, but I've noticed that Widgets (and/or their associated state) hold a strong reference to the (global) eventbus, causing a memory leak. The solution is to cancel the subscription in the widget-state's dispose method, but I'd like to know if there's a better approach (I'm coming from Swift which allows variables to be declared as 'weak').
EDIT
I ended up subclassing the state as follows... any better suggestions?
abstract class CustomState<T extends StatefulWidget> extends State {
List<StreamSubscription> eventSubscriptions = [];
void subscribeToEvent(Object eventClass, Function callback) {
StreamSubscription subscription = eventBus.on(eventClass).listen(callback);
eventSubscriptions.add(subscription);
}
void dispose() {
super.dispose();
eventSubscriptions.forEach((subscription) => subscription.cancel());
eventSubscriptions = null;
}
}
class MyEvent {
String text;
MyEvent(this.text);
}
class _MyHomePageState extends CustomState<MyHomePage> {
#override
void initState() {
super.initState();
subscribeToEvent(MyEvent, onEventFired);
}
void onEventFired(event) {
print('event fired: ${event.runtimeType} ${event.text}');
}
}
Dart doesn't provide weak reference feature.
An Expando has a weak reference behavior though.
Not sure if this is of use in your use case.
https://api.dartlang.org/stable/1.24.3/dart-core/Expando-class.html
https://groups.google.com/a/dartlang.org/forum/m/#!topic/misc/S7GGxegtJe4
What is the Dart "Expando" feature about, what does it do?
https://github.com/dart-lang/sdk/issues/16172
I sometimes use a Mixin that provides a list where I can add subscriptions and a dispose methode that cancels all subscriptions and add it to widgets and other classes where I need it.
As of 2020, I'd like to add to Günter's answer that I've just published a package that goes as close as possible to a weak-reference by implementing a weak-map and a weak-container, as well as cache functions that take advantage of weak references.
https://pub.dev/packages/weak_map
It's much easier to use than an Expando (it uses Expando internally).
Since dart 2.17 you can use WeakReference.
Any object wrapped in WeakReference(obj) is not kept from being garbage collected.
You access the object via the target property which becomes null when the object got garbage collected.
final myWeakRef = WeakReference(ExampleObj());
// access obj, may be null
print(myWeakRef.target);

Are private setters in C++/CX properties a thing?

Is it possible to create/design in a way to privately set a property but only expose the ability to get the properties to the consumers?
I've tackled a multiple inheritance property by making the base class wrapper a member of the concrete classes wrapper. I'd rather not allow someone to write over the base classes instance in the set of it's own property. But I can't seem to exclude set and set the base property and I can't make the set private.
Any ideas?
Code:
ConcreteClassWrapper(); // here I want to setup base class, i.e. give it a pointer to the actual C++ model I'm working with.
property BaseClassWrapper^ BaseClass
{
BaseClassWrapper^ get() { return baseClass; }
// I want to avoid giving my consumers the ability to set this property.
void set(BaseClassWrapper^ value) { baseClass= value; }
}
private:
BaseClassWrapper^ baseClass; // Having a base class wrapper makes it easier on code writing.. i.e. I don't need to implement interfaces. I just want to use my C++ code in C# Microsoft GOD!!!
EDIT:
I'm an idiot, I can access the private member...
This is just one answer... Still want to know why private setters arent' a thing
I just have to access my private member of my ConcreteClassWrapper and set the base class there. Then I can remove the set in the BaseClassWrapper property.
Did you try this :
property BaseClassWrapper^ BaseClass
{
BaseClassWrapper^ get() { return baseClass; }
private:
void set(BaseClassWrapper^ value) { baseClass= value; }
}
This is the way you write a private setter in a property. In the case of C++/CX, the property keyword is just a new keyword to allow C++/CX compiler to generate some C++ code, so the syntax for things like private, public, protected is the same.

Code restricting: Create of more than one object in private constructor in C#

I want to create a code in C# for Private constructor.
I want that it should allow only one object to be created but when I try to create more than one a message showing no more object can be created should be shown.
I don't want to use static constructor in this code.
How do I do that in C#?
You may use static counter or flag that will be set in your private counstructor to show that at least one instance were created.
But first of all, I suggest you to pay attention to Singleton pattern.
Simple, this is the classic singleton pattern:
public class MyClass
{
public static MyClass Instance;
private MyClass()
{
if (Instance != null)
throw new InvalidOperationException("no more object can be created");
// do other constructor logic
Instance = this;
}
}
Please note that synchronization has been left out. This code need synchronization for thread safe purpose.

does dispose method disposes the calling object also?

I found the following code on MSDN:
public class DisposeExample
{
public class MyResource: IDisposable
{
private IntPtr handle;
private Component component = new Component();
private bool disposed = false;
public MyResource(IntPtr handle)
{
this.handle = handle;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if(!this.disposed)
{
if(disposing)
{
// Dispose managed resources.
component.Dispose();
}
CloseHandle(handle);
handle = IntPtr.Zero;
disposed = true;
}
}
~MyResource()
{
Dispose(false);
}
}
public static void Main()
{
MyResource obj = new MyResource()
//obj.dispose()
}
}
Now the confusion I have here is that, if I call obj.dispose, it disposes the objects created in the class MyResources i.e. handle, component etc. But does the obj also gets removed off the heap?? Same applies with the destructor. If I don't call dispose, the destructor will be called sometime. The code inside destructor removes the contained objects. But what about the obj?
Secondly, if I don't have a destructor defined inside the class and I dont even call dispose, does the GC never come into picture here?
IDisposable exists to remove unmanaged items from your managed objects. The runtime automatically provides a destructor, this destructor here has the sole purpose of releasing unmanaged items. As soon as your object goes out of scope or is set to null and has no more references to it will eventually be cleared by the GC.
The fundamental rule I'd recommend with with IDisposable is that at any given moment in time, for every object that implements IDisposable, there should be exactly one entity which has the clearly-defined responsibility of ensuring that it will get cleaned up (almost always by calling Dispose) before it is abandoned. Such responsibility will initially belong to whatever entity calls the IDidposable object's constructor, but that entity may hand the responsibility off to some other entity (which may hand it off again, etc.).
In general, I'd guess that most programmers would be best served if they pretended finalizers and destructors did not exist. They are generally only needed as a consequence of poorly-written code, and in most cases the effort one would have to spend writing a 100%-correct finalizer/destructor and working through all the tricky issues related to threading context, accidental resurrection, etc. could be better spent ensuring that the primary rule given above is always followed. Because of some unfortunate design decisions in the Framework and its languages, there are a few situations which can't very well be handled without finalizers/destructors, but for the most part they serve to turn code which would fail relatively quickly into code which will mostly work but may sometimes fail in ways that are almost impossible to debug.

Confusion with IDisposable

I have some nagging doubts about the correct way to implement IDisposable. Consider the following scenario...
public class Foo : IDisposable {...}
public class Bar : IDisposable {
private bool disposed = false;
private readonly Foo MyFoo;
public Bar() {
this.MyFoo = new Foo();
}
public Bar(Foo foo) {
this.MyFoo = foo;
}
~Bar() {
Dispose(false);
}
protected virtual void Dispose(bool disposing) {
if (!this.disposed) {
if (disposing) {
if (MyFoo != null) {
this.MyFoo.Dispose();
this.MyFoo = null;
}
}
this.disposed = true;
}
}
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
}
My questions are:
1) If a class creates a disposable object, should it call the Dispose() method on that object in its own Dispose() method?
2) If a disposable object is passed to a class as a reference, should that class still call the Dispose() method on that reference object, or should it leave it to the class that created the object in the first place?
The above pattern seems to crop up quite a lot (particularly with DI), but I don't seem to be able to find a concrete example of the correct way to structure this.
Refer to Excellent MSDN article
Garbage Collection: Automatic Memory Management in the Microsoft .NET Framework
1) If a class creates a disposable object, should it call the Dispose() method on that object in its own Dispose() method?
Yes it should. Otherwise also, Dispose will be called. But that will increase life of object by atleast 1 generation. This is due to the finalizer in the class definition. Refer to the article link above.
2) If a disposable object is passed to a class as a reference, should that class still call the Dispose() method on that reference object, or should it leave it to the class that created the object in the first place?
It is responsibility of caller (more specifically the class which has created an instance) to call the Dispose method.
~Bar() {
Dispose(false);
}
Whenever you find yourself writing code like this, take a deep breath first and ask "do I actually need a finalizer?" It is extremely rare that you need one, a finalizer is only required when you take ownership of an unmanaged resource yourself.
The first litmus test is "does the finalizer actually do anything?" That's clear if you follow the code. It calls Dispose(false) and that code only does something when the argument is true. What follows is that you don't need a finalizer. This is entirely normal, finalizers is something that Microsoft worries about. They wrote the .NET framework classes that wrap an unmanaged resource. FileStream, Socket, etcetera. And above all, the SafeHandle classes, designed to wrap operating system handles. They have their own finalizer, you don't rewrite one yourself.
So without a finalizer, the code entirely collapses to the simple and correct implementation, you only need to call the Dispose() method of any disposable objects you store yourself:
public class Bar : IDisposable {
private readonly Foo MyFoo;
public Bar() {
this.MyFoo = new Foo();
}
public void Dispose() {
MyFoo.Dispose();
}
}

Resources