C#

[C#] Abstraction Class vs Interface

An abstract class cannot be instantiated. The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share.

  • An abstract class is a special type of a class that cannot be instantiated.
  • An abstract class should, however, be inherited by its subclasses.
  • Abstract classes are either partially implemented or not implemented at all. You can have functionality in your abstract class — the methods in an abstract class can be both abstract and concrete.
  • An abstract class can have constructors — this is one major difference between an abstract class and an interface.
  • You may take advantage of abstract classes to design components and specify some level of common functionality in the methods of the abstract class until a specific implementation of the abstract class is needed in the class hierarchy.
  • The constructor of an Abstract Class can be called through the derived class constructor.
  • All abstract methods must be implemented in its derived class, if inherited.

An interface contains definitions for a group of related functionalities that a class or a struct can implement.

  • We cannot create an object of an interface, we can only create a reference or Interface Variable.
  • An interface will have only abstract methods (method declaration).
  • Interfaces supports Inheritance, Polymorphism (Overloading, Overriding (using the “new” keyword to hide the interface methods above)).
  • We cannot create variables in an interface.
  • Only Properties, Indexers, Methods and Events are allowed in an interface.
  • A class can inherit multiple interfaces, which is also shown in the snapshot above.
  • We cannot create any Access modifiers with Interface Members (like private, public, protected, internal, protected internal, virtual, override, static, abstract etc.)
  • The new keyword is allowed in an interface.
  • All methods of an interface must be defined in every derived class.

You should use interface if

  • You want to simulate inheritant from struct since struct can’t inherit from another struct or class
  • If the functionality you are creating will be useful across a wide range of disparate objects
  • If you are designing small, concise bits of functionality

You should use abstract class if

  •  It applies to objects that are closely related
  • If you are designing large functional units
  • If you want to provide common, implemented functionality among all implementations of your component

 

C#

[C#] VAR keyword

Beginning in Visual C# 3.0, variables that are declared at method scope can have an implicit “type” var. An implicitly typed local variable is strongly typed just as if you had declared the type yourself, but the compiler determines the type.

In some case like below example, var must be used because the result is a collection of anonymous types, and the name of that type is not accessible except to the compiler itself. Note that in Example #2, the foreach iteration variable item must also be implicitly typed.

// Example #1: var is optional because
// the select clause specifies a string
string[] words = { "apple", "strawberry", "grape", "peach", "banana" };
var wordQuery = from word in words
                where word[0] == 'g'
                select word;

// Because each element in the sequence is a string, 
// not an anonymous type, var is optional here also.
foreach (string s in wordQuery)
{
    Console.WriteLine(s);
}

// Example #2: var is required because
// the select clause specifies an anonymous type
var custQuery = from cust in customers
                where cust.City == "Phoenix"
                select new { cust.Name, cust.Phone };

// var must be used because each item 
// in the sequence is an anonymous type
foreach (var item in custQuery)
{
    Console.WriteLine("Name={0}, Phone={1}", item.Name, item.Phone);
}

 

C#

[C#] REF vs OUT

Both ref and out are used when we want to pass paremeters to a method and allow that method to read and modify data.ref tells the compiler that the object is initialized before entering the function, while out tells the compiler that the object will be initialized inside the function.

So while ref is two-ways, out is out-only.

C#

[C#] Struct vs Class

Classes Only:

  • Can support inheritance
  • Are reference (pointer) types
  • The reference can be null
  • Have memory overhead per new instance

Structs Only:

  • Cannot support inheritance
  • Are value types
  • Cannot have a null reference (unless Nullable is used)
  • Do not have a memory overhead per new instance – unless ‘boxed’
  • Cannot have explicit parameterless constructor
  • Cannot have destructor

Both Classes and Structs:

  • Are compound data types typically used to contain a few variables that have some logical relationship
  • Can contain methods and events
  • Can support interfaces

CONSIDER a struct instead of a class:

  • If instances of the type are small and commonly short-lived or are commonly embedded in other objects.

AVOID a struct unless the type has all of the following characteristics:

  • It logically represents a single value, similar to primitive types (int, double, etc.).
  • It has an instance size under 16 bytes.
  • It is immutable. (cannot be changed)
  • It will not have to be boxed frequently.
C#

[C#] Lock Statement

The lock keyword marks a statement block as a critical section by obtaining the mutual-exclusion lock for a given object, executing a statement, and then releasing the lock. The following example includes a lockstatement.

class Account  
{  
    decimal balance;  
    private Object thisLock = new Object();  

    public void Withdraw(decimal amount)  
    {  
        lock (thisLock)  
        {  
            if (amount > balance)  
            {  
                throw new Exception("Insufficient funds");  
            }  
            balance -= amount;  
        }  
    }  
}

The lock keyword ensures that one thread does not enter a critical section of code while another thread is in the critical section. If another thread tries to enter a locked code, it will wait, block, until the object is released.

You can’t use the await keyword in the body of a lock statement.

 

C#

[C#] Reflection

Reflection provides objects (of type Type) that describe assemblies, modules and types. You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties. If you are using attributes in your code, reflection enables you to access them. For more information, see Attributes.

Here’s a simple example of reflection using the static method GetType – inherited by all types from the Object base class – to obtain the type of a variable:

// Using GetType to obtain type information:  
int i = 42;  
System.Type type = i.GetType();  
System.Console.WriteLine(type);

Result:

System.Int32

The following example uses reflection to obtain the full name of the loaded assembly.

// Using Reflection to get information from an Assembly:  
System.Reflection.Assembly info = typeof(System.Int32).Assembly;  
System.Console.WriteLine(info);

Result:

mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089

Reflection is useful in the following situations: