Something about C# Programming

Published on Sunday, April 20, 2014

Here I collected some content which I noted for C# programming, the content might be from either recent learning courses, or from my real cases in some years ago, but please know the content might not for everybody who are reading this post, mostly, the content might be for myself, a personal notes.

1: Reflection:

Reflection inspects type metadata at runtime (type name, containing assembly, constructors, properties, methods, attributes)

Two methods of Get Type data:

  • Statically at compile time; typeof() – Type type = typeof(obj);
  • Dynamically at runtime: GetType() – Type type = obj.GetType();

Create instance of a Type:

var typeInst = (MyClass)Activator.CreateInstance(typeof(MyClass));        
var myClassConstructor = typeof (MyClass).GEtConstructors(0[0];         
var myClass2 = (MyClass)myClassConstructor.Invoke(null);

Access a Property and Invoking a Method:

public class MyClass() 
{ 
    public string  Name { get; set; }
    public string GetName() 
    { 
        return "Alex"; 
    } 
}

void Property() 
{ 
    var myClass = new MyClass() {Name = "Tony"}; 
    var type = myClass.GetType(); 
    var name = type.GetProperty("Name"); 
    var value = name.GetValue(myClass, null); 
    //output:  value = "Tony" 
} 
void Method() 
{ 
    var myClass = new MyClass(); 
    var type = myClass.GetType(); 
    var method = type.GetMethod("GetName"); 
    var value = (string)method.Invoke(myClass, null); 
    //output:  value = "Alex" 
} 

__More:

var myProperties = myClass.GetType().GetProperties(); 
foreach(System.Reflection.PropertyInfo pInfo in myProperties) 
{ 
    if(pInfo.Name.Equals("Name", StringComparison.InvariantCulture)) 
    { 
        //To do… 
    } 
} 

2: About Garbage Collection:

  • Garbage collection is automatic memory management
  • De-referenced objects (orphans) are not collected immediately but periodically.
    Many factors influence Garbage Collection frequency
    Not all orphans are collected at the same time
  • Garbage Collection is computationally expensive

Forcing Garbage Collection:

GC.Collect();        
GC.WaitForPendingFinalizers();         
GC.Collect();

Disposable Objects:

void MyClass : IDisposable     
{}

sample from Microsoft:

using System;

class BaseClass : IDisposable 
{ 
   // Flag: Has Dispose already been called? 
   bool disposed = false;

   // Public implementation of Dispose pattern callable by consumers. 
   public void Dispose() 
   { 
      Dispose(true); 
      GC.SuppressFinalize(this);           
   }

   // Protected implementation of Dispose pattern. 
   protected virtual void Dispose(bool disposing) 
   { 
      if (disposed) 
         return;

      if (disposing) { 
         // Free any other managed objects here. 
         // 
      }

      // Free any unmanaged objects here. 
      // 
      disposed = true; 
   }

   ~BaseClass() 
   { 
      Dispose(false); 
   } 
} 
///////////////

using System;

class DerivedClass : BaseClass 
{ 
   // Flag: Has Dispose already been called? 
   bool disposed = false;

   // Protected implementation of Dispose pattern. 
   protected override void Dispose(bool disposing) 
   { 
      if (disposed) 
         return;

      if (disposing) { 
         // Free any other managed objects here. 
         // 
      }

      // Free any unmanaged objects here. 
      // 
      disposed = true; 
   } 
}

3: Advanced Validation:

System.Diagnostics.Contracts.Contract.Requires 
    (!string.IsNullOrWhiteSpace(myString), "myString is empty");

System.Diagnostics.Contracts.Contract.Ensures 
     (!string.IsNullOrWhiteSpace(Contract.Result<string>()));

4: Boxing and Unboxing:

int i = 123;

// The following line boxes i. 
object o = i; o = 123;

i = (int)o;  // unboxing

Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type. Unboxing extracts the value type from the object.
Boxing is implicit; unboxing is explicit.

Above example: object is actually a pointer which point to a heap location which store real value, but when you set i to o, system first arrange a heap room to store real value, then set i’s value to the real place, this is the process of Boxing. unboxing is the revert process.

Please read Microsoft sample here to get details.