Wednesday, May 11, 2011

Interface (C# Reference)

An interface contains only the signatures of methods, delegates or events. The implementation of the methods is done in the class that implements the interface, as shown in the following example:
interface ISampleInterface
{
    void SampleMethod();
}

class ImplementationClass : ISampleInterface
{
    // Explicit interface member implementation: 
    void ISampleInterface.SampleMethod()
    {
        // Method implementation.
    }

    static void Main()
    {
        // Declare an interface instance.
        ISampleInterface obj = new ImplementationClass();

        // Call the member.
        obj.SampleMethod();
    }
}

An interface can be a member of a namespace or a class and can contain signatures of the following members:
An interface can inherit from one or more base interfaces.
When a base type list contains a base class and interfaces, the base class must come first in the list.

The following example demonstrates interface implementation. In this example, the interface IPoint contains the property declaration, which is responsible for setting and getting the values of the fields. The class Point contains the property implementation.
// keyword_interface_2.cs
// Interface implementation
using System;
interface IPoint
{
   // Property signatures:
   int x
   {
      get;
      set;
   }

   int y
   {
      get;
      set;
   }
}

class Point : IPoint
{
   // Fields:
   private int _x;
   private int _y;

   // Constructor:
   public Point(int x, int y)
   {
      _x = x;
      _y = y;
   }

   // Property implementation:
   public int x
   {
      get
      {
         return _x;
      }

      set
      {
         _x = value;
      }
   }

   public int y
   {
      get
      {
         return _y;
      }
      set
      {
         _y = value;
      }
   }
}

class MainClass
{
   static void PrintPoint(IPoint p)
   {
      Console.WriteLine("x={0}, y={1}", p.x, p.y);
   }

   static void Main()
   {
      Point p = new Point(2, 3);
      Console.Write("My Point: ");
      PrintPoint(p);
   }
}

Static Class and Static Constructor

Static constructors have the following properties:
  • A static constructor does not take access modifiers or have parameters.
  • A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.
  • A static constructor cannot be called directly.
  • The user has no control on when the static constructor is executed in the program.
  • A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.
  • Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the LoadLibrary method.
A Constructor is usually used to initialize data. However Static Constructor is used to initialize only static members. Here I am just talking about the Constructors. How they get initialized and how they behave.

Things to know about Static Constructor

  1. It is used to initialize static data members. 
  2. Can't access anything but static members.
  3. Can't have parameters
  4. Can't have access modifiers like Public, Private or Protected.
Now once you understand the above points, you can appreciate the difference between Static Class and Unstatic Class
  1. Static Class cannot be instantiated unlike the unstatic class. You should directly access its Method via the ClassName.MethodName
  2. A Program can't tell when it is going to load static class but its definitely loaded before the call.
  3. A Static class will always have the static constructor and its called only once since after that its in the memory for its lifetime.
  4. A Static class can contain only static members. So all the members and functions have to be static.
  5. A Static class is always sealed since it cannot be inherited further. Further they cannot inherit form any other class (except Object)
Let's look at a normal Constructor

class
 Program{    static void Main(string[] args)
      { 


         /* Note two things
        1.Here you get to instantiate the Constructor in the code wherever you like.
        2.If you debug you get to goto the Constructor and see what is being done.
         */         MyExample myExample = new MyExample();
         myExample.Print();
      }
}
public class MyExample{    private static int StaticVariable ;    public MyExample()
       {
             if (StaticVariable < 10)
             {
                    StaticVariable = 20; 
             }
            else             {
                   StaticVariable = 100; 
             }
       }
  
    public void Print()
    {
        Console.WriteLine(StaticVariable);
    } 
}
Now consider this second example for static class
class Program{    static void Main(string[] args)
    {
       /* Note the following
            1.You dont get to instantiate for sure so you dont know when the constructor was called.
            2.Secondly you can access your method directly.
       */
      //MyExampleStatic myExampleStatic = new MyExampleStatic();       MyExampleStatic.Print();
}
}

static class MyExampleStatic{    private static int StaticVariable;    static MyExampleStatic()
   {
        if (StaticVariable < 10)
          {
          StaticVariable = 20;
          }
    else     {
          StaticVariable = 100;
      }
  }
    public static void Print()
   {
        Console.WriteLine(StaticVariable);
    }
}

C# : Difference between Hashtable and Dictionary

When we want a collection  data structure to hold data as key/value pairs, we have two obvious choices.
So basically what is the difference between both this and when to use which. Lets check it out. Point by Point.
1) Generics
Dictionary is a generic type, Hashtable is not. Now what that means. This is the most important aspect one should consider when taking decision. Dictionary is a generic type means
- You get type safety with Dictionary, because you can't insert any random object into it, and you don't have to cast the values you take out.
- And also generic collections are a lot faster as there's no boxing/unboxing
- Hashtable uses Object to hold things internally (Only non-generic way to do it). So you have to take care of type safety and cast it to appropriate data type when you take it out, but it also means that you can add keys and values of any type ( It is good or bad, well it depends :) )
- Again Hashtable also have to box/unbox, which may have memory consumption as well as performance penalties.
2) Thread Safety :
In .Net Hashtable is thread safe for use by multiple reader threads and a single writing thread, while in Dictionary public static members are thread safe, but any instance members are not guaranteed to be thread safe.
One more thing that can make difference is,  we can not use dictionary (generics) with web services. The reason is no web service standard supports generics standard.

Encapsulation and data Abstraction

Abstraction Revolves around identifying the Physical and Logical (incl of 
Semi Physical) classes that are present in a system. 
Encapsulation Revolves around Saying this specific class that is identified 
during abstraction can be given to the user like this.... 

If I have said that I am going for a Student information system. The One who 
says you that a class called Student is required is Abstraction. The class 
student should not know how to update his marks is what is 
specified/implemented through the Encapsulation. Note that the rule which I 
mentioned above is the result of your understanding of the 
system(Abstraction). So the baseline is your Data Abstraction is a bird 
view of the total system. The things which you model are specified at 
abstraction level only.... It is the starting point for your Building of a 
System. 

As a Developer we decide that this specific user should understand the 
system upto this level only... for instance the Student information System 
assumes that the student can only see his marks he can not edit it. So the 
student view of the system is simplified to the user that is student. 
Better example is Your Bike. You know about your bike to an extent that is 
to drive, fill petrol and so on. For you it is not reqd to know how to 
Repair if it stuck in between. So the bike is offering you an interface 
through which you can work with it without bothering what is happening 
inside...Same is the case with Student. The System is allowing him to see 
his marks without bothering him to understand what a Teacher is doing... 
Sahil ofcourse Meant this... 

So A Perfect System that is modeled carefully will give the user a role 
based access in which the users will be offered an interface to perform the 
action without knowing the internal stuff. Abstraction is Preceedes 
Encapsulation in giving the user this kind of a Behaviour... 

Finally: these definitions are very specific to Me and Me only... But 
whatever some one says that can be boiled down to this points. 
Abstraction : Understanding and hmmmmmmmmmm... there are many 
Data Abstarction : 
1. Understanding of a System. 
2. Collection of Sub Systems to form a SuperSystem. 
You Call a Car as A "CAR" not " the One with a 4 wheels and 
blab la" 
Encapsulation: 
1. Grouping up the Data / Hiding the Data 
2. After identifying the classes one should know which 
behaviour should be exposed to whom??? Answer is encapsulation. 

So please never get confused with the definition (what is it?) and 
implication(How does it matter/ what is that it do???)... 

OOPS!! I am Tired... I'll Rest Here... still some more doubts on OOP terms 
... Never mind to shoot me bak.... 

Thursday, May 5, 2011

Object Oriented --

1.Public Private and Internal or Friend these access modifier can use for class

2.Public Private and Internal or Friend ,Protected and internal protected can we
used with Method

3. no Access modifier Allowed in Interface (Inside interface means for method or
property).for declaring interface u can use public or internal

4.for defining Abstract class u can  use internal or public class .for  abstract
method u can  use only public  access modifier (no  internal,protected) .without
abstract method u can use any Access modifier.

5.Abstract Method Can not be marked as Virtual.and at the time of implementation
of Abstract Method  we have to  use Keywaord Override  .u can not  use "NEW" key
word at the time of implemmentation of Abstract Method

6.if any class have an Abstract Method this class called Abstract Class.

7.Sealed keyword for method can we used with override keyword only.

8. Condition--Class  A is  inheriting in  Class B  and Class  B is inheriting in
Class C There is an condition where  one method(Base class A ) is overriding  in
derived  class(Class B)  now again  I want  to override  this method   again in
derived class(Class C). is it possible  if yes how Answer-Yes with the  same key
Word Override if we want to Stop  to override this class then we can  use Sealed
keyword

9.How to call base class method (which keyword will use )

10.Can u use virtual in base class and NEW in derived class  --- Yes

11.Can u override an method which is hideing the base class method (by using New
KeyWord)--Yes

12.Static Method can not access an instance member.

13.We can convert the integer “i” using “i.ToString()” or “Convert.ToString”  so
what’s the difference.The  basic difference between  them is “Convert”  function
handles  NULLS  while “i.ToString()”does  not  it will  throw  a NULL  reference
exception error. So as good coding practice using “convert” is always safe.

14.Serialization is the process of converting  an object into a stream of  bytes
in order to persist it to memory, a database, or a file. Its main purpose is  to
save the state of an object in order to be able to recreate it when needed.  The
reverse process is called deserialization.

15 Attributes provide  a powerful  method of  associating metadata,  or declarative
information, with code (assemblies,  types, methods, properties, and  so forth).
After an attribute  is associated with  a program entity,  the attribute can  be
queried  at  run  time  by  using  a  technique  called  reflection.

16.Application domains provide a flexible and secure method of isolating running
applications.

Application  domains  are usually  created  and manipulated  by  run-time hosts.
Occasionally, you may  want your application  to programmatically interact  with
your application domains, for example,  to unload a component without  having to
stop your application from running.

Application domains aid  security, separating applications  from each other  and
each other's data.  A single process  can run several  application domains, with
the same  level of  isolation that  would exist  in separate  processes. Running
multiple applications within a single process increases server scalability.

Static and Dynamic binding

Static Binding :
Example 1 :
public class MyClass
{
   public void DoSomething(){...}
}

public class MyOtherClass
{
   public MyOtherClass()
   {
      MyClass mc = new MyClass();
      mc.DoSomething();
   }
}

Dynamic Binding :
Example 2 :

public abstract class WidgetBase
{
   public abstract void DoSomething();
}

public class ShinyWidget : WidgetBase
{
   public override void DoSomething()
   {
      // implementation
   }
}

public class DullWidget : WidgetBase
{
   public override void DoSomething()
   {
      // implementation
   }
}

public class MyOtherClass
{
   public void DoSomethingWithAWidget(WidgetBase widget)
   {
      widget.DoSomething();
   }
}