I am currently trying to implement my first dispose on some of my objects, and was wondering if its a bad idea to go through all the properties per reflection and just set them to null?
76867
Should you set all the objects to null (Nothing in VB.NET) once you have finished with them?   I understand that in .NET it is essential to dispose of any instances of objects that implement the IDisposable interface to release some resources although the object can still be something after it is disposed (hence the isDisposed property in forms), so I assume it can still reside in memory or at least in part?  I also know that when an object goes out of scope it is then marked for collection ready for the next pass of the garbage collector (although this may take time).  So with this in mind will setting it to null speed up the system releasing the memory as it does not have to work out that it is no longer in scope and are they any bad side effects?  MSDN articles never do this in examples and currently I do this as I cannot  see the harm. However I have come across a mixture of opinions so any comments are useful.
35959
I've been programming in C# and Java recently and I am curious where the best place is to initialize my class fields.  Should I do it at declaration?:  public class Dice {     private int topFace = 1;     private Random myRand = new Random();      public void Roll()     {        // ......     } }   or in a constructor?:  public class Dice {     private int topFace;     private Random myRand;      public Dice()     {         topFace = 1;         myRand = new Random();     }      public void Roll()     {         // .....     } }   I'm really curious what some of you veterans think is the best practice. I want to be consistent and stick to one approach.
96827
I have the following class which uses BinaryReader internally and implements IDisposable.   class DisposableClass : IDisposable     {         private BinaryReader reader;         public DisposableClass(Stream stream)         {             reader = new BinaryReader(stream);         }          protected virtual void Dispose(bool disposing)         {             if (disposing)             {                 ((IDisposable)reader).Dispose(); //                reader.Dispose();// this won't compile             }         }          public void Dispose()         {             this.Dispose(true);         }     }   I have already figured out that I need to cast BinaryReader to IDisposable to be able to call Dispose on it, but I don't understand why I can't just call the Dispose() method directly without casting to IDisposable?
8224
Since many users are facing the NullReferenceException: Object reference not set to an instance of an object error in Unity, I thought that it would be a good idea to gather from multiple source some explanation and ways to fix this error.  Symptoms I am getting the error below appearing in my console, what does it mean and how do I fix it?  NullReferenceException: Object reference not set to an instance of an object
44134
Is there a setting in Resharper 4 (or even Visual Studio itself...) that forces a warning if I forget to wrap code in a using block, or ommit the proper Dispose call in a finally block?
3286
Does the order in which I set properties using the object initializer syntax get executed in the exact same order?  For instance if I do this:  var s = new Person { FirstName = "Micah",                      LastName = "Martin",                      IsLoaded = true                    }   will each property get set in the same order?
78597
I keep getting the System.NullPointerException: Attempt to de-reference a null object on my trigger at line 21. I've attempted to add != null to that line and I get an error too. Please see the code below.  trigger UpdateDMAAccount on Account (before insert, before update) { //get set of Postal Codes from leads to be inserted or updated Set&lt;String&gt; BillingpostalCodes = new Set&lt;String&gt;(); for(Account l : trigger.new){ if(l.BillingPostalCode != null){     BillingpostalCodes.add(l.BillingPostalCode);  } } if(BillingpostalCodes.size() &gt; 0){ //create Map of custom object records with Name (PostalCode) as key Map&lt;String,DMA_Value__c&gt; validBillingPostalCode = new Map&lt;String,DMA_Value__c&gt;(); for(DMA_Value__c obj : [SELECT Id, Name, DMA_Value__c FROM DMA_Value__c WHERE Name IN :BillingpostalCodes]){     validBillingPostalCode.put(obj.Name,obj); } for(Account l : trigger.new){     if((Trigger.isInsert || trigger.oldMap.get(l.Id).BillingPostalCode != l.BillingPostalCode) &amp;&amp; validBillingPostalCode.containsKey(l.BillingPostalCode)){          l.DMA__c = validBillingPostalCode.get(l.BillingPostalCode).DMA_Value__c;     }     else if(trigger.oldMap.get(l.Id).BillingPostalCode != NULL || l.BillingPostalCode &amp;&amp; !validBillingPostalCode.containsKey(l.BillingPostalCode)){         //blank value if new PostalCode does not match a record in the Map         l.DMA__c = Null;     }   }  } }
22005
I see a lot of example code for C# classes that does this:  public class Point {     public int x { get; set; }     public int y { get; set; } }   Or, in older code, the same with an explicit private backing value and without the new auto-implemented properties:  public class Point {     private int _x;     private int _y;      public int x {         get { return _x; }         set { _x = value; }     }      public int y {         get { return _y; }         set { _y = value; }     } }   My question is why. Is there any functional difference between doing the above and just making these members public fields, like below?  public class Point {     public int x;     public int y; }   To be clear, I understand the value of getters and setters when you need to do some translation of the underlying data. But in cases where you're just passing the values through, it seems needlessly verbose.
25669
I know from reading  that the "primary" use of the IDisposable interface is to clean up unmanaged resources.  To me, "unmanaged" means things like database connections, sockets, window handles, etc.  But, I've seen code where the Dispose() method is implemented to free managed resources, which seems redundant to me, since the garbage collector should take care of that for you.  For example:  public class MyCollection : IDisposable {     private List&lt;String&gt; _theList = new List&lt;String&gt;();     private Dictionary&lt;String, Point&gt; _theDict = new Dictionary&lt;String, Point&gt;();      // Die, clear it up! (free unmanaged resources)     public void Dispose()     {         _theList.clear();         _theDict.clear();         _theList = null;         _theDict = null;     }   My question is, does this make the garbage collector free memory used by MyCollection any faster than it normally would?  edit:  So far people have posted some good examples of using IDisposable to clean up unmanaged resources such as database connections and bitmaps.  But suppose that _theList in the above code contained a million strings, and you wanted to free that memory now, rather than waiting for the garbage collector.  Would the above code accomplish that?
38112
Here's the scenario...    if (entry.Properties["something"].Value != null)   attribs.something = entry.Properties["something"].Value.ToString();   While effective and working correctly, this looks ugly to me.  If I don't check for a null before performing the ToString() then it throws an exception if the property was null.  Is there a better way to handle this scenario?  Much appreciated!
78703
If have this in the setter of a property:  decimal? temp = value as decimal?;   value = "90"  But after the cast, temp is null...  What is the proper way to do this cast?
22388
How do you give a C# auto-property an initial value?  I either use the constructor, or revert to the old syntax.    Using the Constructor:  class Person  {     public Person()     {         Name = "Initial Name";     }     public string Name { get; set; } }   Using normal property syntax  (with an initial value)  private string name = "Initial Name"; public string Name  {     get      {         return name;     }     set     {         name = value;     } }   Is there a better way?
16225
Why does it (apparently) make a difference whether I pass null as an argument directly, or pass an Object that I assigned the value null?  Object testVal = null; test.foo(testVal);    // dispatched to foo(Object) // test.foo(null);    // compilation problem -&gt; "The method foo(String) is ambiguous"     public void foo(String arg) { // More-specific     System.out.println("foo(String)"); }  public void foo(Object arg) { // Generic     System.out.println("foo(Object)"); }   In other words, why is the (commented-out) second call to foo(...) not dispatched to foo(Object)?  Update: I use Java 1.6. I could compile Hemal's code without problems, but mine still doesn't compile. The only difference I see is that Hemal's methods are static while mine are not. But I really don't see why this should make a difference...?  Update 2: Solved. I had another method foo(Runnable) in my class, so the dispatcher couldn't unambiguously select the single most specific method. (See my comment in Hemal's second answer.) Thanks everyone for your help.
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.
2935
I am fascinated by the way the CLR and GC works (I'm working on expanding my knowledge on this by reading CLR via C#, Jon Skeet's books/posts, and more).  Anyway, what is the difference between saying:  MyClass myclass = new MyClass(); myclass = null;   Or, by making MyClass implement IDisposable and a destructor and calling Dispose()?  Also, if I have a code block with a using statement (eg below), if I step through the code and exit the using block, is the object disposed of then or when a garbage collection occurs? What would happen if I call Dispose() in the using block anyay?  using (MyDisposableObj mydispobj = new MyDisposableObj()) {  }   Stream classes (eg BinaryWriter) have a Finalize method? Why would I want to use that?
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]
38591
class someclass {};  class base {     int a;     int *pint;     someclass objsomeclass;     someclass* psomeclass; public:     base()     {         objsomeclass = someclass();         psomeclass = new someclass();         pint = new int();          throw "constructor failed";         a = 43;     } }  int main() {     base temp(); }   In the above code, the constructor throws. Which objects will be leaked, and how can the memory leaks be avoided?  int main() {     base *temp = new base(); }   How about in the above code? How can the memory leaks be avoided after the constructor throws?