It's important to mention that the question is about an owned object which its lifecycle will be controlled by the container it is declared in.   For an external object which has been assigned from outside which lifecycle is not controlled by the container class, it is neccessary to unsubscribe its event handler when the class will be disposed/destroyed to avoid memory leaks.   public class ContainerClass: IDisposable {     private INotifyPropertyChanged SomeNotifyObject = new SomeNotifyPropertyChangeedImplementingClass();      public ContainerClass()     {         SomeNotifyObject.PropertyChanged += SomeNotifyObjectOnPropertyChanged;     }      // Neccessary if ContainerClass OWNS the subscribed object?     void IDisposable.Dispose()     {         SomeNotifyObject.PropertyChanged -= SomeNotifyObjectOnPropertyChanged;     }      private void SomeNotifyObjectOnPropertyChanged(object sender, PropertyChangedEventArgs e)     {         // Stuff     } }   If the anser is no, it is not neccessary in case of an owned object, code could be written less complex:  private INotifyPropertyChanged SomeNotifyObject = SomeNotifyPropertyChangeedImplementingClass();      public ContainerClass()     {         SomeNotifyObject.PropertyChanged += (sender, args) =&gt;         {             /* Call whatever you want */         };     } }
45838
If I have the following code:  MyClass pClass = new MyClass(); pClass.MyEvent += MyFunction; pClass = null;   Will pClass be garbage collected? Or will it hang around still firing its events whenever they occur? Will I need to do the following in order to allow garbage collection?  MyClass pClass = new MyClass(); pClass.MyEvent += MyFunction; pClass.MyEvent -= MyFunction; pClass = null;
8134
The  says that public class SomeObject {   public void SomeOperation()   {     lock(this)     {       //Access instance variables     }   } }  is &quot;a problem if the instance can be accessed publicly&quot;. I'm wondering why? Is it because the lock will be held longer than necessary? Or is there some more insidious reason?
32609
Is there any way to automatically get notified of property changes in a class without having to write OnPropertyChanged in every setter?  (I have hundreds of properties that I want to know if they have changed).    Anton suggests .  I've actually used the "Castle" library for something similar in the past, and while it does reduce the amount of code I've had to write, it added around 30 seconds to my program startup time (ymmv) - because it's a runtime solution.  I'm wondering if there is a compile time solution, maybe using compile-time attributes...    Slashene and TcKs give suggestions which generates repetitive code - unfortunately, not all my properties are a simple case of m_Value = value - lots of them have custom code in the setters, so cookie-cutter code from snippets and xml aren't really feasible for my project either.
53887
I have seen a few mentions of this idiom (including ):  // Deliberately empty subscriber public event EventHandler AskQuestion = delegate {};   The upside is clear - it avoids the need to check for null before raising the event.  However, I am keen to understand if there are any downsides.  For example, is it something that is in widespread use and is transparent enough that it won't cause a maintenance headache?  Is there any appreciable performance hit of the empty event subscriber call?
29575
If I call finalize() on an object from my program code, will the JVM still run the method again when the garbage collector processes this object?  This would be an approximate example:  MyObject m = new MyObject();  m.finalize();  m = null;  System.gc()   Would the explicit call to finalize() make the JVM's garbage collector not to run the finalize() method on object m?
54935
How would you go about finding out how much memory is being used by an object? I know it is possible to find out how much is used by a block of code, but not by an instantiated object (anytime during its life), which is what I want.
93507
In C#, is there a way to instantiate an instance of a class without invoking its constructor?  Assume the class is public and is defined in a 3rd party library and the constructor is internal.  The reasons I want to do this are complicated but it would be helpful to know if it's possible using some kind of C# hackery.  NOTE: I specifically do not want to call any constructor so using reflection to access the internal constructor is not an option.
14
I want to do something like:  MyObject myObj = GetMyObj(); // Create and fill a new object MyObject newObj = myObj.Clone();   And then make changes to the new object that are not reflected in the original object.  I don't often need this functionality, so when it's been necessary, I've resorted to creating a new object and then copying each property individually, but it always leaves me with the feeling that there is a better or more elegant way of handling the situation.  How can I clone or deep copy an object so that the cloned object can be modified without any changes being reflected in the original object?
3658
I have a non-visual component which manages other visual controls.    I need to have a reference to the form that the component is operating on, but i don't know how to get it.  I am unsure of adding a constructor with the parent specified as control, as i want the component to work by just being dropped into the designer.  The other thought i had was to have a Property of parent as a control, with the default value as 'Me'  any suggestions would be great  Edit:  To clarify, this is a component, not a control, see here :
71403
When would I implement IDispose on a class as opposed to a destructor?  I read , but I'm still missing the point.    My assumption is that if I implement IDispose on an object, I can explicitly 'destruct' it as opposed to waiting for the garbage collector to do it.  Is this correct?  Does that mean I should always explicitly call Dispose on an object?  What are some common examples of this?
18334
Take the following C# class:  c1 {  event EventHandler someEvent; }   If there are a lot of subscriptions to c1's someEvent event and I want to clear them all, what is the best way to achieve this? Also consider that subscriptions to this event could be/are lambdas/anonymous delegates.  Currently my solution is to add a ResetSubscriptions() method to c1 that sets someEvent to null. I don't know if this has any unseen consequences.
48735
I recently implemented a class like:  class TestClass : IDisposable {     RegistryKey m_key;     public TestClass()     {         m_key = Registry.CurrentUser.OpenSubKey("Software", false);     }      public void Dispose()     {         // m_key.Dispose();         IDisposable disp = m_key;         disp.Dispose();     } }   If I uncomment the direct call to Dispose, I get error CS0117 ("'Microsoft.Win32.RegistryKey' does not contain a definition for 'Dispose'").  Some Googling led me to , where I learned what was going on, so I now understand the mechanics of it.  The  documentation suggests that the author would prefer that I call Close() instead of Dispose(), but doesn't explain why.  What is the purpose of this pattern (which I think I've seen it in the IO classes as well)?  In light of the fact that this was an intentional decision by the class author, how bad is the code above (the call to Dispose through the IDisposable interface)?  It can't be too bad - after all, it's what would happen in a using statement, right?  [edits: 1) changed title from "non-public" to "explicit" 2) removed the explicit implementation from my code, accidentally left in from experimentation]
69794
Should objects be disposed when using the client object model?  If so, which ones?  There seems to be plenty of information on this for server side, but nothing from Microsoft specifically about client side.
37236
I know that calling a virtual method from a base class constructor can be dangerous since the child class might not be in a valid state. (at least in C#)  My question is what if the virtual method is the one who initializes the state of the object ? Is it good practice or should it be a two step process, first to create the object and then to load the state ?  First option: (using the constructor to initialize the state)  public class BaseObject {     public BaseObject(XElement definition) {         this.LoadState(definition);     }      protected abstract LoadState(XElement definition); }   Second option: (using a two step process)  public class BaseObject {     public void LoadState(XElement definition) {         this.LoadStateCore(definition);     }      protected abstract LoadStateCore(XElement definition); }   In the first method the consumer of the code can create and initialize the object with one statement:  // The base class will call the virtual method to load the state. ChildObject o = new ChildObject(definition)   In the second method the consumer will have to create the object and then load the state:  ChildObject o = new ChildObject(); o.LoadState(definition);
81142
I have a object that is my in memory state of the program and also have some other worker functions that I pass the object to to modify the state. I have been passing it by ref to the worker functions. However I came across the following function.  byte[] received_s = new byte[2048]; IPEndPoint tmpIpEndPoint = new IPEndPoint(IPAddress.Any, UdpPort_msg); EndPoint remoteEP = (tmpIpEndPoint);  int sz = soUdp_msg.ReceiveFrom(received_s, ref remoteEP);    It confuses me because both received_s and remoteEP are returning stuff from the function. Why does remoteEP need a ref and received_s does not?  I am also a c programmer so I am having a problem getting pointers out of my head.  Edit: It looks like that objects in C# are pointers to the object under the hood. So when you pass an object to a function you can then modify the object contents through the pointer and the only thing passed to the function is the pointer to the object so the object itself is not being copied.  You use ref or out if you want to be able to switch out or create a new object in the function which is like a double pointer.
35227
I have created a custom WPF user control which is intended to be used by a third party. My control has a private member which is disposable, and I would like to ensure that its dispose method will always get called once the containing window/application is closed. However, UserControl is not disposable. I tried implementing the IDisposable interface and subscribing to the Unloaded event but neither get called when the host application closes. MSDN says that the Unloaded event may not be raised at all. And it might also be triggered more than once, that is when user changes theme. If at all possible, I don't want to rely on consumers of my control remembering to call a specific Dispose method.  public partial class MyWpfControl : UserControl  {      SomeDisposableObject x;       // where does this code go?      void Somewhere()       {          if (x != null)          {              x.Dispose();              x = null;          }       }  }  The only solution I have found so far is to subscribe to the Dispatcher's ShutdownStarted event. Is this a reasonable approach? this.Dispatcher.ShutdownStarted += Dispatcher_ShutdownStarted;
121546
In my understanding of Servlet, the Servlet will be instantiated by the Container, its init() method will be called once, and the servlet will live like a singleton until the JVM shuts down.  I do not expect my servlet to be serialized, since it will be constructed new when the app server recovers or is starts up normally. The servlet should hold no session-specific members, so it does not make sense for it to be written to disk and re-instantiated. Is there a practical use for this?  My concerns are, that I put some non-serializable fields within there and then my app will mysteriously fail in a production environment where a different sort of session replication will take place.