User Tools

Site Tools


snippets:start

C# Code snippets

Design mode

Gotcha: DesignMode property is not valid in constructor, use Load event instead.

Byte size to human readable units

      private static String SizeToHumanReadable (long sizeInBytes)
      {
                string[] units = { "B", "KiB", "MiB", "GiB", "TiB", "PiB" };
                double len = sizeInBytes;
                int order = 0;
                int maxOrder = units.Length - 1;
                while (len >= 1024 && order < maxOrder) {
                        order++;
                        len = len / 1024;
                }
                return String.Format (CultureInfo.InvariantCulture, "{0:0.000} {1}", len, units[order]);
        }

Retrieve currently logged in user

System.Security.Principal.WindowsIdentity.GetCurrent()

Debugging code

To declare code that is active for a configuration only prefer using attribute against #ifdef's for more readable code: [Conditional(“DEBUG”)]

For displaying user string representation of classes in the debugger, prefer using the DebuggerDisplay attribute to overriding ToString as the latter is used by String.Format primarily:

[DebuggerDisplay("Count = {count}")]
class MyHashtable
{
    public int count = 4;
}

Temporary File

using System.IO;
FileInfo tempFile = new FileInfo(Path.GetTempFileName());
...
tempFile.Delete();

Getting path of executable

Assembly.GetEntryAssembly().Location

implementing IDisposable

// Design pattern for a base class.
public class Base: IDisposable
{
    private bool disposed = false;
 
    //Implement IDisposable.
    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
 
    protected virtual void Dispose(bool disposing)
    {
        if (!disposed) {
            if (disposing) {
                // Free other state (managed objects).
            }
            // Free your own state (unmanaged objects).
            // Set large fields to null.
            disposed = true;
        }
    }
 
    // Use C# destructor syntax for finalization code.
    ~Base()
    {
        // Simply call Dispose(false).
        Dispose (false);
    }
}
// Design pattern for a derived class.
public class Derived: Base
{
    private bool disposed = false;
 
    protected override void Dispose(bool disposing)
    {
        if (!disposed) {
            if (disposing) {
                // Release managed resources.
            }
            // Release unmanaged resources.
            // Set large fields to null.
           // Call Dispose on your base class.
            disposed = true;
        }
        base.Dispose(disposing);
    }
    // The derived class does not have a Finalize method
    // or a Dispose method without parameters because it inherits
    // them from the base class.
}

  

snippets/start.txt · Last modified: 2015/07/26 15:08 by jaap.dehaan