Thursday, October 12, 2017

Interface and Abstract class in c#

Interfaces is very general concept of object oriented programming. Here are few fundamentals rules associated with interfaces in c# -

- Interfaces can contain methods, properties, events, indexers, or any combination of those four member types.
- An interface can't contain constants, fields, operators, instance constructors, finalizers, or types.
- Interface members are automatically public, and they can't include any access modifiers. Members also can't be static.
- Interfaces can implement other interfaces.
- A class might include an interface multiple times through base classes that it inherits or through interfaces that other interfaces implement. However, the class can provide an implementation of an interface only one time and only if the class declares the interface as part of the definition of the class (class ClassName : InterfaceName). If the interface is inherited because you inherited a base class that implements the interface, the base class provides the implementation of the members of the interface. However, the derived class can reimplement the interface members instead of using the inherited implementation.

Abstract Class -
Abstract class is class which has atleast 1 abstract method. Abstract class can inherit from non abstract class. When an abstract class inherits a virtual method from a base class, the abstract class can override the virtual method with an abstract method.
public class D
{
    public virtual void DoWork(int i)
    {
        // Original implementation.
    }
}

public abstract class E : D
{
    public abstract override void DoWork(int i);
}

public class F : E
{
    public override void DoWork(int i)
    {
        // New implementation.
    }
}
If a virtual method is declared abstract, it is still virtual to any class inheriting from the abstract class. A class inheriting an abstract method cannot access the original implementation of the method—in the previous example, DoWork on class F cannot call DoWork on class D. In this way, an abstract class can force derived classes to provide new method implementations for virtual methods.

Sealed Class:-
A sealed class cannot be used as a base class. For this reason, it cannot also be an abstract class. Sealed classes prevent derivation. Because they can never be used as a base class, some run-time optimizations can make calling sealed class members slightly faster.
A method, indexer, property, or event, on a derived class that is overriding a virtual member of the base class can declare that member as sealed. This negates the virtual aspect of the member for any further derived class. This is accomplished by putting the sealed keyword before the override keyword in the class member declaration.
The sealed keyword enables you to prevent the inheritance of a class or certain class members that were previously marked virtual.

Multithreading concept in c#

Difference in keyword used -

Concurrent
several thhings going in parallel
several things happening at once
might or might not be mutithread

Mutithreading
uses OS capabuility to porcess multiple operations
Multiple execution context
more than 1 thread, might or might not be concurrent

Parallel
multi simultaneous computations
more on hardware level -
multi core CPU - multiple processing at once

Asynchronous
not having to wait

Context Switch -
It is OS level concept. When the thread/process are executing any code and CPU needs to execute some other instruction, then it stores the state of current thread like register state and all in memory and store the other thread.
Ref - http://www.linfo.org/context_switch.html

Process, Thread and Apartment
Ref - https://msdn.microsoft.com/library/windows/desktop/ms693344.aspx

An application domain forms an isolation boundary for security, versioning, reliability, and unloading of managed code. A thread is the operating system construct used by the common language runtime to execute code. At run time, all managed code is loaded into an application domain and is run by one or more managed threads.
There is not a one-to-one correlation between application domains and threads. Several threads can execute in a single application domain at any given time, and a particular thread is not confined to a single application domain. That is, threads are free to cross application domain boundaries; a new thread is not created for each application domain.

Understanding STA & MTA-
The COM threading model is called an "apartment" model, where the execution context of initialized COM objects is associated with either a single thread (Single Thread Apartment) or many threads (Multi Thread Apartment). In this model, a COM object, once initialized in an apartment, is part of that apartment for the duration of its runtime.

The STA model is used for COM objects that are not thread safe. That means they do not handle their own synchronization. A common use of this is a UI component. So if another thread needs to interact with the object (such as pushing a button in a form) then the message is marshalled onto the STA thread. The windows forms message pumping system is an example of this.

If the COM object can handle its own synchronization then the MTA model can be used where multiple threads are allowed to interact with the object without marshalled calls.

"var" keyword in c#

REF - https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/var

"var" keyword is given by c# to declare a variable. It can help us avoid writing "type" on LHS of the expression. even though we are not writing type before the variable name, but it does not mean that it doesnt have a type. compiler defines the type by evaluating the RHS of the expression. It is more a implicit type definition.

"var" can not be used at class level to define the fields. if you refer this article -
 https://blogs.msdn.microsoft.com/ericlippert/2009/01/26/why-no-var-on-fields/
It states about compilation process of c# compiler.
First we run through every source file and do a "top level only" parse. That is, we identify every namespace, class, struct, enum, interface, and delegate type declaration at all levels of nesting. We parse all field declarations, method declarations, and so on. In fact, we parse everything except method bodies; those, we skip and come back to them later.
Once we've done that first pass we have enough information to do a full static analysis to determine the type of everything that is not in a method body. We make sure that inheritance hierarchies are acyclic and whatnot. Only once everything is known to be in a consistent, valid state do we then attempt to parse and analyze method bodies. We can then do so with confidence because we know that the type of everything the method might access is well known.
There's a subtlety there. The field declarations have two parts: the type declaration and the initializer. The type declaration that associates a type with the name of the field is analyzed during the initial top-level analysis so that we know the type of every field before method bodies are analyzed. But the initialization is actually treated as part of the constructor; we pretend that the initializations are lines that come before the first line of the appropriate constructor.
So immediately we have one problem; if we have "var" fields then the type of the field cannot be determined until the expression is analyzed, and that happens after we already need to know the type of the field.

Here are the rules with "var" keyword -
- "var" can only be used when a local variable is declared and initialized in the same statement; the variable cannot be initialized to null, or to a method group or an anonymous function.
- "var" cannot be used on fields at class scope.
- Variables declared by using "var" cannot be used in the initialization expression. In other words, this expression is legal: int i = (i = 20); but this expression produces a compile-time error: var i = (i = 20);
- Multiple implicitly-typed variables cannot be initialized in the same statement.
- If a type named "var" is in scope, then the var keyword will resolve to that type name and will not be treated as part of an implicitly typed local variable declaration.

Extension Methods in C#

Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type.
The most common extension methods are the LINQ standard query operators that add query functionality to the existing System.Collections.IEnumerable and System.Collections.Generic.IEnumerable types

Example -
namespace ExtensionMethods
{
    public static class MyExtensions
    {
        public static int WordCount(this String str)
        {
            return str.Split(new char[] { ' ', '.', '?' },
                             StringSplitOptions.RemoveEmptyEntries).Length;
        }
    }
}

In above code we invoke the extension method with instance method syntax. However, the intermediate language (IL) generated by the compiler translates our code into a call on the static method.Extension methods cannot access private variables in the type they are extending.

You can use extension methods to extend a class or interface, but not to override them. An extension method with the same name and signature as an interface or class method will never be called. At compile time, extension methods always have lower priority than instance methods defined in the type itself. In other words, if a type has a method named Process(int i), and you have an extension method with the same signature, the compiler will always bind to the instance method. When the compiler encounters a method invocation, it first looks for a match in the type's instance methods. If no match is found, it will search for any extension methods that are defined for the type, and bind to the first extension method that it finds.

ref: -https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/extension-methods