Wednesday, July 20, 2016

Shadowing in c#

Shadowing in c#


new keyword explicitly hides member that is inherited from the base class (base class method is hidden or we can say derived class replaces/hides the base method) 

When you hide an inherited member, the derived version of the member replaces the base class version.


* It is an error to use both new and override on the same member, because the two modifier have mutually exclusive meanings. The new modifier creates a new member with the same name and causes the original member to become hidden. The override modifier extends the implementation for an inherited member.

public class BaseC
{
public int x;
public void invoke()
{
}
}

public class DerivedC : BaseC
{
   nenw public void Invoke()
   {
    }
}

Design patterns c#

Design patterns c#

Singleton pattern

When we want only one instance of the object to be created and shared between clients (global variables of project)

To achieve/implement singleton pattern

1. Define the constructor as private, so no instance/object can be created
2. Define instance (variables) and methods as static. This will cause one global instance to be created and shared across.

E.g.

Public class clsSingleton
{
  public static int intCounter;
  private clsSingleton()
    {
       //This is a private constructor
     }

   public static void Hits()
    {
         intCounter++;
     }
    public static int getTotalHits()
     {
        return intCounter;
      }
}

Client Code
clsSingleton.Hit();                 //Everytime counter increments by 1


Factory Pattern

public class clsFactoryInvoice
{
  public static IInvoice getInvoice(int intInvoiceType)
  {
    IInvoice objInv;
    if(intInvoiceType == 1)
    {
      objInv = new clsInvoiceWithHeader();
    }
    else if (intInvoiceType ==2)
    {
        objInv = new clsInvoiceWithoutHeader();
     }
     else
      { return null;}
    return objInv;
  }
}

public interface IInvoice
{
  public void print();
}

public class clsInvoiceWithHeader : IInvoice
{
  public void print()
  {
     console.writelinne("Invoice will be printed with header");
   }
}

public class clsInvoiceWithoutHeader : IInvoice
{
  public void print()
  {
     console.writelinne("Invoice will be printed without header");
   }
}


Benefits : Client no need to know which all concrete classes available (loosely coupled) client will have object created just by passing parameter.

Sunday, July 17, 2016

Assembly

Assembly

Assembly form the fundamental unit of deployment, version control, reuse.
Assembly take the form of an executable (.exe) file or dynamic link library (.dll) file. They provide the CLR with information it needs to be aware of type implementation.
You can think of an assembly as a collection of types and resources that forms a logical unit of functionality and are built to work together.



Assembly Contents
1. Assembly manifest which contains metadata
2. Type metadata
3. MSIL code that implements the type
4. Set of resources

Assemblies have the following properties

  • Assemblies are implementated as .exe or .dll files
  • You can share an assembly between applications by putting in the GAC. Assembly must be strong-named before they can included in GAC
  • Assemblies are only loaded in the memory if they are required. if they are not required they are not loaded
  • You can problematically obtain information about an assembly by using reflection.

Assembly Manifest

Within every assembly is an assembly manifest.
Assembly manifest contains the following

  • The assembly identity (its name & version) make up the assembly for e.g. any other  assemblies you created that your .exe or .dll relies on
  • An assembly reference list - External dependency such as GAC or somewhat like system 32 directory.

Assembly Contents

In general, a static assembly can consists of four elements.
  • The assembly manifest, which contains assembly metadata
  • Type metadata
  • Microsoft Intermediate Language (MSIL) code that implements types
  • A set of resources

Metadata

Metadata is a binary information describing your program that is stored either in a common language runtime portable executable (PE) file or in memory. When you compile your code into PE file, metadata is inserted into one portion of the file and your code is converted to Microsoft  intermediate language (MSIL) and inserted into another portion of the file.
Every type and member that is referential in a module or assembly is described within metadata. When code is executed, the runtime loads metadata into memory and references it to discover information about you code's classes, members , instances and so on.

Language interoperability : Metadata provides all the information required about compiled code for you inherit a class from a PE file written in different language you can created an instance of any class written in any managed language (any language that targets the common language runtime) without worrying about explicit marshaling or using custom interoperabilty code.

MSIL
When compiling to managed code, the compiler translates your source code into MSIL, which is CPU independent set of instruction that can be efficiently converted to native code. Before code can be run, MSIL must be converted to native code, usually by a Just-In-Time (JIT) compiler


Wednesday, July 6, 2016

Types of constructors

Types of constructors

1. Instance Constructor
2. Static Constructor (gets called only once)
3. Private Constructor


Static Constructor

 A static constructor is used to initialize any static data or to perform a particular action that needs to be performed once automatically before the first instance is created or any static members are referenced.

E.G.

Class SimpleClass
{
static readonly long x;
//static constructor is called at most one time
//before any constructor is invoked or member is accessed

Static SimpleClass()
{
x = DateTime.Now.Ticks;
}
}

Important points to note

  • A static constructor does not take access modifier or have parameters
  • A static constructor cannot be called directly
  • Users have no control only when the static constructor is executed in the program
  • A typical use of static constructor is when the class is using a log file and constructor is used to write entries
  • We can have both static constructor and instance constructor in same class

Private Constructor

If a class has one or more private constructor *and no public constructor* other class cannot create instance of this class (expect nested class).
We can have both private & public constructor in same class if parameters are different.

By default constructor is private. If we try to create instance of a class having private constructor, you will get constructor is inaccessible due to its protection level


========================================================================

Unless a class is static, class without constructor are given a public default by c# compiler in order to enable class instantiation.


Moral : A class must have public constructor for creating its object


========================================================================

Copy constructor : c# doesn't provide constructor  for objects, but we can create


E.g.

class Person
{
//Copy constructor
public Person (Person prevPerson)
{
Name = prevPerson.Name;
Age = prevPerson.Age
}


//Below is parameterized constructor public Person (string name, int age)
{
Person P1 = new Person("George", 40);
Person P2 = new Person (P1);
}
}

Sunday, July 3, 2016

Try-Catch

Try-Catch

  1. Generalized exception catch block should be at the end in case of multiple catch block. If we declare generalized catch block at starting then it will give compile time error. Error :                  Already declared in super class
  2. We can have return statement in catch block
  3. We can have break statement in catch block if loop is present inside catch
  4. Finally block can't have return statement
  5. Finally block can have other try-catch block.
  6. Finally block can have break statement inside the loop
  7. If exception occurs in finally, execution will break/stop
  8. Try block should at least  have finally block if catch block is not provided


Nested Try Catch scenario


i. If divide by zero exception encounters in outer try block then outer try block will execute
ii. In case of inner try block exception, inner catch block will execute
iii. If divide by zero exception encounters in inner try block and if we don't have inner catch block specific for divide by zero and if we have outer catch block which specifically handles divide by zero then outer catch block will be executed.

Ref and Out parameters in c#


ref out param in c#


REF OUT
REF must be initialized before it passes to method OUT its not necessary, but after method call it should get initialized
Extra performance cost Faster
The called method can read argument at anytime The called method must initialize the parameter before using it
ref parameters are used to get a value and return a change to that value Out parameters are useed whe you just need to get a secondary return value


==================================================================

REF



Class tryref
{
  public void (ref int i, ref int j)
  {
     j = i*j;

  }
 }


Calling program

Class Program
{
static void main (string[] args)
{
tryref tf = new tryref();
int i = 5;
int j = 10;
console.writeline("The value of i and j before the call : "+i","+j);
tf.mul(ref i, ref j);
console.writeline("The value of i and j after the call : "+i","+j);
}

}

=======================================================================

OUT



class tryout
{
public int mul (int a, out int b)
{
b = a*a;
return b;
}

}

Calling Program

Class Program
{
static void Main(string [] args)
{
tryout to = new tryout();
// passing out parameter j and getting returning value
to.mul(5, out j);
console.writeline("The value of  j is :"+j);
}

}

========================================================================

Why we use ref and out parameters in C#.



Lets say  we call some method and value of variable changes in that method. However as per method functioning we only receive whatever returned by method i.e. for e.g. method returns integer we get integer value.
When we want to capture the changed value which happened in "called" method we use ref/out parameter irrespective of what method is returning.

Constant, Readonly and Static readonly

Constant, Readonly and Static readonly

Constant Readonly Static readonly
cant be changed runtime. Run time constant Global value for all instances of the class. Can be changed only once at runtime.
cant be changed runtime. you can initialize value of variable only once at runtime in a constructor Can be changed only once at runtime.