Use full notes.....

1. Introduction
1.1 What is C#?
C# is a general-purpose object-oriented programming language designed by Microsoft. It is loosely based on C/C++, and is very similar to Java. You can download the C# 3.0 spec here.
1.2 How do I develop C# apps?
Visual C# Express is the easiest way to get started. On Linux you can use Mono.
1.3 Does C# replace C++?
There are three options open to the Windows developer from a C++ background:

  • Stick with standard C++. Don't use .NET at all.
  • Use C++ with .NET. Microsoft supply a .NET C++ compiler that produces IL rather than machine code. (To make full use of the .NET environment (e.g. garbage collection), a set of extensions are required to standard C++, called C++/CLI.)
  • Forget C++ and use C#.
Each of these options has merits, depending on the developer and the application, but for most general purpose applications C# is a much more productive environment than C++. Where existing C++ code must be used with a new application, the existing code can be wrapped using C++/CLI to allow it to interop with C#.
1.4 Does C# have its own class library?
Not exactly. The .NET Framework has a comprehensive class library, which C# can make use of. C# does not have its own class library.
2. Types
2.1 What standard types does C# use?
C# supports a very similar range of basic types to C++, including int, long, float, double, char, string, arrays, structs and classes. However, don't assume too much. The names may be familiar, but many of the details are different. For example, a long is 64 bits in C#, whereas in C++ the size of a long depends on the platform (typically 32 bits on a 32-bit platform, 64 bits on a 64-bit platform). Also classes and structs are almost the same in C++ - this is not true for C#. Finally, chars and strings in .NET are 16-bit (Unicode/UTF-16), not 8-bit like C++.
2.2 Is it true that all C# types derive from a common base class?
Yes and no. All types can be treated as if they derive from object (System.Object), but in order to treat an instance of a value type (e.g. int, float) as object-derived, the instance must be converted to a reference type using a process called 'boxing'. In theory a developer can forget about this and let the run-time worry about when the conversion is necessary, but in reality this implicit conversion can have side-effects that may trip up the unwary.
2.3 So I can pass an instance of a value type to a method that takes an object as a parameter?
Yes. For example:
   class CApplication
   {
       public static void Main()
       {
           int x = 25;
           string s = "fred";
       
           DisplayMe( x );
           DisplayMe( s );
       }
   
       static void DisplayMe( object o )
       {
           System.Console.WriteLine( "You are {0}", o );
       }
   }
This would display:
   You are 25
   You are fred
2.4 What are the fundamental differences between value types and reference types?
C# divides types into two categories - value types and reference types. Most of the intrinsic types (e.g. int, char) are value types. Structs are also value types. Reference types include classes, arrays and strings. The basic idea is straightforward - an instance of a value type represents the actual data, whereas an instance of a reference type represents a pointer or reference to the data.
The most confusing aspect of this for C++ developers is that C# has predetermined which types are represented as values, and which are represented as references. A C++ developer expects to take responsibility for this decision.
For example, in C++ we can do this:
   int x1 = 3;        // x1 is a value on the stack
   int *x2 = new int(3)    // x2 is a pointer to a value on the heap
but in C# there is no control:
   int x1 = 3;        // x1 is a value on the stack
   int x2 = new int();
   x2 = 3;        // x2 is also a value on the stack!
2.5 Okay, so an int is a value type, and a class is a reference type. How can int be derived from object?
It isn't, really. When an int is being used as an int, it is a value. However, when it is being used as an object, it is a reference to an integer value (on the managed heap). In other words, when you treat an int as an object, the runtime automatically converts the int value to an object reference. This process is called boxing. The conversion involves copying the int to the heap, and creating an object instance which refers to it. Unboxing is the reverse process - the object is converted back to a value.
   int x = 3;        // new int value 3 on the stack
   object objx = x;    // new int on heap, set to value 3 - still have x=3 on stack
   int y = (int)objx;    // new value 3 on stack, still got x=3 on stack and objx=3 on heap
2.6 Are C# references the same as C++ references?
Not quite. The basic idea is the same, but one significant difference is that C# references can be null . So you cannot rely on a C# reference pointing to a valid object. In that respect a C# reference is more like a C++ pointer than a C++ reference. If you try to use a null reference, a NullReferenceException is thrown.
For example, look at the following method:
   void displayStringLength( string s )
   {
       Console.WriteLine( "String is length {0}", s.Length );
   }        
The problem with this method is that it will throw a NullReferenceException if called like this:
   string s = null;
   displayStringLength( s );
Of course for some situations you may deem a NullReferenceException to be a perfectly acceptable outcome, but in this case it might be better to re-write the method like this:
   void displayStringLength( string s )
   {
       if( s == null )
           Console.WriteLine( "String is null" );
       else
           Console.WriteLine( "String is length {0}", s.Length );
   }        
2.7 Can I use typedefs in C#?
No, C# has no direct equivalent of the C++ typedef. C# does allow an alias to be specified via the using keyword:
   using IntList = System.Collections.Generic.List<int>;
but the alias only applies in the file in which it is declared. A workaround in some cases is to use inheritance:
   public class IntList : List<int> { }
The pros and cons of this approach are discussed here.
3. Classes and Structs
3.1 Structs are largely redundant in C++. Why does C# have them?
In C++, a struct and a class are pretty much the same thing. The only difference is the default visibility level (public for structs, private for classes). However, in C# structs and classes are very different. In C#, structs are value types (instances stored directly on the stack, or inline within heap-based objects), whereas classes are reference types (instances stored on the heap, accessed indirectly via a reference). Also structs cannot inherit from structs or classes, though they can implement interfaces. Structs cannot have destructors. A C# struct is much more like a C struct than a C++ struct.
3.2 Does C# support multiple inheritance (MI)?
No, though it does support implementation of multiple interfaces on a single class or struct.
3.3 Is a C# interface the same as a C++ abstract class?
No, not quite. An abstract class in C++ cannot be instantiated, but it can (and often does) contain implementation code and/or data members. A C# interface cannot contain any implementation code or data members - it is simply a group of method names & signatures. A C# interface is more like a COM interface than a C++ abstract class.
3.4 Are C# constructors the same as C++ constructors?
Very similar, but there are some significant differences. First, C# supports constructor chaining. This means one constructor can call another:
   class Person
   {
       public Person( string name, int age ) { ... }
       public Person( string name ) : this( name, 0 ) {}
       public Person() : this( "", 0 ) {}
   }
Another difference is that virtual method calls within a constructor are routed to the most derived implementation - see Can I Call a virtual method from a constructor.
Error handling is also somewhat different. If an exception occurs during construction of a C# object, the destuctor (finalizer) will still be called. This is unlike C++ where the destructor is not called if construction is not completed. (Thanks to Jon Jagger for pointing this out.)
Finally, C# has static constructors. The static constructor for a class runs before the first instance of the class is created.
Also note that (like C++) some C# developers prefer the factory method pattern over constructors. See Brad Wilson's article.
3.5 Are C# destructors the same as C++ destructors?
No. They look the same but they are very different. The C# destructor syntax (with the familiar ~ character) is just syntactic sugar for an override of the System.Object Finalize method. This Finalize method is called by the garbage collector when it determines that an object is no longer referenced, before it frees the memory associated with the object. So far this sounds like a C++ destructor. The difference is that the garbage collector makes no guarantees about when this procedure happens. Indeed, the algorithm employed by the CLR garbage collector means that it may be a long time after the application has finished with the object. This lack of certainty is often termed 'non-deterministic finalization', and it means that C# destructors are not suitable for releasing scarce resources such as database connections, file handles etc.
To achieve deterministic destruction, a class must offer a method to be used for the purpose. The standard approach is for the class to implement the IDisposable interface. The user of the object must call the Dispose() method when it has finished with the object. C# offers the 'using' construct to make this easier.
Note that it's rarely necessary to define a destructor for a C# class - it only makes sense where the class holds direct references to unmanaged resources, which is very unusual. Implementing IDisposable is somewhat more commonly required, but still only necessary for a small minority of classes.
3.6 If C# destructors are so different to C++ destructors, why did MS use the same syntax?
Presumably they wanted C++ programmers to feel at home. I think they made a mistake.
3.7 Are all methods virtual in C#?
No. Like C++, methods are non-virtual by default, but can be marked as virtual.
3.8 How do I declare a pure virtual function in C#?
Use the abstract modifier on the method. The class must also be marked as abstract. Note that abstract methods cannot have an implementation (unlike pure virtual C++ methods).
3.9 Can I call a virtual method from a constructor/destructor?
Yes, but it's generally not a good idea. The mechanics of object construction in .NET are quite different from C++, and this affects virtual method calls in constructors.
C++ constructs objects from base to derived, so when the base constructor is executing the object is effectively a base object, and virtual method calls are routed to the base class implementation. By contrast, in .NET the derived constructor is executed first, which means the object is always a derived object and virtual method calls are always routed to the derived implementation. (Note that the C# compiler inserts a call to the base class constructor at the start of the derived constructor, thus preserving standard OO semantics by creating the illusion that the base constructor is executed first.)
The same issue arises when calling virtual methods from C# destructors. A virtual method call in a base destructor will be routed to the derived implementation.
3.10 Should I make my destructor virtual?
A C# destructor is really just an override of the System.Object Finalize method, and so is virtual by definition.
4. Exceptions
4.1 Can I use exceptions in C#?
Yes, in fact exceptions are the recommended error-handling mechanism in C# (and in .NET in general). Most of the .NET framework classes use exceptions to signal errors.
4.2 What types of object can I throw as exceptions?
Only instances of the System.Exception classes, or classes derived from System.Exception. This is in sharp contrast with C++ where instances of almost any type can be thrown.
4.3 Can I define my own exceptions?
Yes, just derive your exception class from System.Exception.
Note that if you want your exception to cross remoting boundaries you'll need to do some extra work - see http://www.thinktecture.com/Resources/RemotingFAQ/CustomExceptions.html for details.
4.4 Does the System.Exception class have any cool features?
Yes - the feature which stands out is the StackTrace property. This provides a call stack which records where the exception was thrown from. For example, the following code:
   using System;

   class CApp
   {  
       public static void Main()
       {
           try
           {
               f();
           }
           catch( Exception e )
           {
               Console.WriteLine( "System.Exception stack trace = \n{0}", e.StackTrace );
           }
       }

       static void f()
       {
           throw new Exception( "f went pear-shaped" );
       }
   }
produces this output:
   System.Exception stack trace =
       at CApp.f()
       at CApp.Main()
Note, however, that this stack trace was produced from a debug build. A release build may optimise away some of the method calls which could mean that the call stack isn't quite what you expect.
4.5 When should I throw an exception?
This is the subject of some debate, and is partly a matter of taste. However, it is accepted by most that exceptions should be thrown only when an 'unexpected' error occurs. How do you decide if an error is expected or unexpected? This is a judgement call, but a straightforward example of an expected error is failing to read from a file because the seek pointer is at the end of the file, whereas an example of an unexpected error is failing to allocate memory from the heap.
4.6 Does C# have a 'throws' clause?
No, unlike Java, C# does not require (or even allow) the developer to specify the exceptions that a method can throw.
5. Run-time Type Information
5.1 How can I check the type of an object at runtime?
You can use the is keyword. For example:
   using System;

   class CApp
   {
       public static void Main()
       {
           string s = "fred";
           long i = 10;

           Console.WriteLine( "{0} is {1}an integer", s, (IsInteger(s) ? "" : "not ") );
           Console.WriteLine( "{0} is {1}an integer", i, (IsInteger(i) ? "" : "not ") );
       }
   
       static bool IsInteger( object obj )
       {
           if( obj is int || obj is long )
               return true;
           else
               return false;
       }
   }
produces the output:
   fred is not an integer
   10 is an integer
5.2 Can I get the name of a type at runtime?
Yes, use the GetType method of the object class (which all types inherit from). For example:
   using System;

   class CTest
   {
       class CApp
       {
           public static void Main()
           {
               long i = 10;
               CTest ctest = new CTest();

               DisplayTypeInfo( ctest );
               DisplayTypeInfo( i );
           }
       
           static void DisplayTypeInfo( object obj )
           {
               Console.WriteLine( "Type name = {0}, full type name = {1}", obj.GetType(), obj.GetType().FullName );
           }
       }
   }
produces the following output:
   Type name = CTest, full type name = CTest
   Type name = Int64, full type name = System.Int64
5.3 What is the difference between typeof and GetType()?
Apart from the obvious (i.e. typeof operates on a type whereas GetType operates on an object), the main thing to watch out for is that GetType returns the underlying type of the object, which may not be the same as the type of the reference to the object. For example:
   class Base { }
   class Derived : Base { }

   class Program
   {
       static void Main()
       {
           ShowType( new Derived() );
       }

       static void ShowType( Base b )
       {
           Console.WriteLine(typeof(Base));
           Console.WriteLine(b.GetType());
       }
   }
gives the following output:
   Base
   Derived
6. Miscellaneous
6.1 How do I do a case-insensitive string comparison?
Use the string.Compare method. Its third parameter specifies case sensitivity.
   "fred" == "Fred"    // false
   string.Compare( "fred", "Fred", StringComparison.CurrentCultureIgnoreCase ) == 0    // true
For more control over the comparison, e.g. exotic features like width-sensitivity, consider using System.Globalization.CompareInfo.Compare(), e.g.
   CultureInfo.CurrentCulture.CompareInfo.Compare(
       "fred", "Fred",
       CompareOptions.IgnoreCase |
       CompareOptions.IgnoreKanaType |
       CompareOptions.IgnoreWidth
       );
6.2 Does C# support a variable number of arguments?
Yes, using the params keyword. The arguments are specified as a list of arguments of a specific type, e.g. int. For ultimate flexibility, the type can be object. The standard example of a method which uses this approach is System.Console.WriteLine().
6.3 How can I process command-line arguments?
Like this:
   using System;

   class CApp
   {
       public static void Main( string[] args )
       {
           Console.WriteLine( "You passed the following arguments:" );
           foreach( string arg in args )
               Console.WriteLine( arg );
       }
   }
(Take a look at Charles Cook's NOptFunc project for easy command-line parsing.)
6.4 Does C# do array bounds checking?
Yes. An IndexOutOfRange exception is used to signal an error.
6.5 How can I make sure my C# classes will interoperate with other .NET languages?
Make sure your C# code conforms to the Common Language Subset (CLS). To help with this, add the [assembly:CLSCompliant(true)] global attribute to your C# source files. The compiler will emit an error if you use a C# feature which is not CLS-compliant.
6.6 How do I use the 'using' keyword with multiple objects?
You can nest using statements, like this:
   using( obj1 )
   {
       using( obj2 )
       {
           ...    
       }
   }
However consider using this more aesthetically pleasing (but functionally identical) formatting:
   using( obj1 )
   using( obj2 )
   {
       ...
   }
6.7 What is the difference between == and object.Equals?
For value types, == and Equals() usually compare two objects by value. For example:
   int x = 10;
   int y = 10;
   Console.WriteLine( x == y );
   Console.WriteLine( x.Equals(y) );
will display:
   True
   True
However things are more complex for reference types. Generally speaking, for reference types == is expected to perform an identity comparison, i.e. it will only return true if both references point to the same object. By contrast, Equals() is expected to perform a value comparison, i.e. it will return true if the references point to objects that are equivalent. For example:
   StringBuilder s1 = new StringBuilder("fred");
   StringBuilder s2 = new StringBuilder("fred");
   Console.WriteLine( s1 == s2 );
   Console.WriteLine( s1.Equals(s2) );
will display:
   False
   True
s1 and s2 are different objects (hence == returns false), but they are equivalent (hence Equals() returns true).
Unfortunately there are exceptions to these rules. The implementation of Equals() in System.Object (the one your class inherits by default) compares identity, i.e. it's the same as operator==. So Equals() only tests for equivalence if the class author overrides the method (and implements it correctly). Another exception is the string class - its operator== compares value rather than identity.
Bottom line: If you want to perform an identity comparison use the ReferenceEquals() method. If you want to perform a value comparison, use Equals() but be aware that it will only work if the type has overridden the default implementation. Avoid operator== with reference types (except perhaps strings), as it's simply too ambiguous.
6.8 How do I enforce const correctness in C#?
You can't - at least not in the same way you do in C++. C# (actually, the CLI) has no real concept of const correctness, For example, there's no way to specify that a method should not modify an argument passed in to it. And there's no way to specify that a method does not modify the object on which it is acting.
To get a feel for the angst this causes among some C++ programmers, read the feedback on this post from Raymond Chen.
There are of course ways of addressing this issue. For example, see Brad Abram's post (and associated feedback) for some ideas on adding optional read-only behaviour to collection classes.
7. C# 2.0
7.1 What are the new features in C# 2.0?
Support for all of the new framework features such as generics, anonymous methods, partial classes, iterators and static classes. See the .NET FAQ for more on these features.
Delegate inference is a new feature of the C# compiler which makes delegate usage a little simpler. It allows you to write this:
   Thread t = new Thread(ThreadFunc);
instead of this:
   Thread t = new Thread( new ThreadStart(ThreadFunc) );
Another minor but welcome addition is the explicit global namespace, which fixes a hole in namespace usage in C# 1.x. You can prefix a type name with global:: to indicate that the type belongs to the global namespace, thus avoiding problems where the compiler infers the namespace and gets it wrong.
Finally C# 2.0 includes some syntactic sugar for the new System.Nullable type. You can use T? as a synonym for System.Nullable<T>, where T is a value type. As suggested by the name, this allows values of the type to be 'null', or 'undefined'.
7.2 Are C# generics the same as C++ templates?
No, not really. There are some similarities, but there are also fundamental differences. See the .NET FAQ for more details.
8. C# 3.0
8.1 What's new in C# 3.0?
Support for LINQ was the driving force behind the main enhancements in C# 3.0. Query expressions are the most obvious example, but lambda expressions, extension methods and anonymous types also fall into this category. However most of these enhancements are useful beyond LINQ.
Query expressions allow a SQL-like query syntax to be used in C#, e.g.
   var nameList = new List<string> { "jack", "jill", "sue" };

   var results = from name in nameList
       where name.StartsWith("j")
       select name;
Query expressions are just syntactic sugar - they resolve to standard method calls. For example the query expression above can be rewritten as:
   var results = nameList.Where(name => name.StartsWith("j"));
The argument to Where() is a lambda expression, which represents an anonymous method. However a lambda expression is not just a more concise way to represent executable code - it can also be interpreted as a data structure (known as an expression tree), which allows the expression to be easily analysed or transformed at runtime. For example, LINQ-to-SQL makes use of this feature to transform C# queries to SQL queries, which gives much better performance than a simple in-memory filtering of results (as offered by DataTable.Select(), for example).
The Where() method shown above is an example of another new C# 3.0 feature: extension methods. Extension methods allow extra methods to be 'attached' to an existing type - any type, even sealed types or types you don't have the source code for. For example, the Where() method can be applied to any type that implements IEnumerable<T>.

Another new feature of C# 3.0 is the
var keyword, which allows the compiler to infer the type of a variable from context, which is required for anonymous types but can be used with standard named types too:
   var list = new List<string>() { "jack", "jill", "sue" };    // optional use with named types

   var person = new { name = "jack", age = 20 };     // anonymous type
These examples also demonstrate the new object initializer and collection initializer syntax.
Finally, there are implicitly typed arrays and auto-implemented properties:
   var names = new [] { "jack", "jill", "sue" };    // implicitly string[]

   public string Name { get; set; }    // auto-implemented property - private backing field auto-generated
Early Binding And Late Binding.......

if the base class object wants to call the function of derived class ,it will get the reference of base class function at run time since there is association between base class to derived class at compile time. this is late binding..
(
class A{}
class B:A{}
class c:b{}
)
In the above program child class has already known the reference of parent class like we can say that when child has the reference of any parent class then it is earlier known to that child to which class it is derived...
So, Here is Early binding
But Any parent class don't have the reference of any child we have to give it explicitly by some process or mechanism (virtual and abstract keyword) and at run time parent class will take the reference of his child class because pointer mechanism starts at run time not compile-time....
..............................................Topic Starts here.................................................







Early and Late Biding
.........................
if the type of object is deterministic means type of object(class name) is confirm before creation of object and this object allocates memory by new keyword. we can say this object is early bound with confirm type.
If there is a class name employee. we create the object of this class as................
employee ravi=new employee();

here one thing is clear that ravi is of type employee; so we can say ravi is early bounded. we can not assign any other object type to ravi object...
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''.
if the type of object is no-deterministic means type of object is not known before execution of program. the type of object points to a particular class at run time. This process is called late binding since the object takes decision to which class it have to point is determined late(run time).

an object is late bounded when it is assigned to a variable declared to be of type Object. Objects of this type can hold references to any object.

................................................................
if the dll is loaded at compile time by syntax :>csc /t:library prg.cs ,the dll is early bounded to program......
if the dll is loaded at run time by the use of reflection , this is late binding;

Derived class has the the reference of the base class before creation of object of derived class. means derived class is early bounded to base class. so the derived class object can determine at compile time which function has to be called of base class or derived class..

we should use early-bound objects whenever possible, because they allow the compiler to make important optimizations that yield more efficient applications. Early-bound objects are significantly faster than late-bound objects and make your code easier to read and maintain by stating exactly what kind of objects are being used. Another advantage to early binding is that it enables useful features such as automatic code completion. Early binding also reduces the number of run time errors.

1. Introduction
I have noticed an increase in the number of articles published in the Architect category in code-project during the last few months. The number of readers for most of these articles is also high, though the ratings for the articles are not. This indicates that readers are interested in reading articles on Architecture, but the quality does not match their expectations. This article is a constructive attempt to group/ define/ explain all introductory concepts of software architecture for well seasoned developers who are looking to take their next step as system architects.
One day I read an article that said that the richest 2 percent own half the world's wealth. It also said that the richest 1 percent of adults owned 40 percent of global assets in the year 2000. And further, that the richest 10 percent of adults accounted for 85 percent of the world's total wealth. So there is an unbalanced distribution of wealth in the physical world. Have you ever thought of an unbalanced distribution of knowledge in the software world? According to my view point, the massive expansion of the software industry is forcing developers to use already implemented libraries, services and frameworks to develop software within ever shorter periods of time. The new developers are trained to use (I would say more often) already developed software components, to complete the development quicker. They just plug in an existing library and some how manage to achieve the requirements. But the sad part of the story is, that they never get a training to define, design the architecture for, and implement such components. As the number of years pass by, these developers become leads and also software architects. Their titles change, but the old legacy of not understanding, of not having any architectural experience continues, creating a vacuum of good architects. The bottom line is that only a small percentage of developers know how to design a truly object oriented system. The solution to this problem is getting harder every day as the aggressive nature of the software industry does not support an easy adjustment to existing processes, and also the related online teaching materials are either complex or less practical or sometimes even wrong. The most of them use impractical, irrelevant examples of shapes, animals and many other physical world entities to teach concepts of software architecture. There are only very few good business-oriented design references. Unfortunately, I myself am no exception and am a result of this very same system. I got the same education that all of you did, and also referred to the same resource set you all read.
Coming back to the initial point, I noticed that there is a knowledge gap, increasing every day, between the architects who know how to architect a system properly and the others who do not know. The ones, who know, know it right. But the ones, who do not know, know nothing. Just like the world’s wealth distribution, it is an unbalanced distribution of knowledge.
2. Background
This article began after reading and hearing the questions new developers have, on basics of software architecture. There are some good articles out there, but still developers struggle to understand the basic concepts, and more importantly, the way to apply them correctly.
As I see it, newcomers will always struggle to understand a precise definition of a new concept, because it is always a new and hence unfamiliar idea. The one, who has experience, understands the meaning, but the one who doesn’t, struggles to understand the very same definition. It is like that. Employers want experienced employees. So they say, you need to have experience to get a job. But how the hell is one supposed to have that experience if no one is willing to give him a job? As in the general case, the start with software architecture is no exception. It will be difficult. When you start to design your very first system, you will try to apply everything you know or learned from everywhere. You will feel that an interface needs to be defined for every class, like I did once. You will find it harder to understand when and when not to do something. Just prepare to go through a painful process. Others will criticize you, may laugh at you and say that the way you have designed it is wrong. Listen to them, and learn continuously. In this process you will also have to read and think a lot. I hope that this article will give you the right start for that long journey.
The knowledge of the actions of great men, acquired by long experience in contemporary affairs, and a continual study of antiquity” – I read this phrase when I was reading the book named “The Art of War”, seems applicable here, isn’t it?
3. Prerequisites
This article is an effort to provide an accurate information pool for new developers on the basics of software architecture, focusing on Object Oriented Programming (OOP). If you are a developer, who has a minimum of three or more years of continuous development experience and has that hunger to learn more, to step-in to the next level to become a software architect, this article is for you.
4. The Main Content
4.1. What is Software Architecture?
Software Architecture is defined to be the rules, heuristics and patterns governing:
  • Partitioning the problem and the system to be built into discrete pieces
  • Techniques used to create interfaces between these pieces
  • Techniques used to manage overall structure and flow
  • Techniques used to interface the system to its environment
  • Appropriate use of development and delivery approaches, techniques and tools.
4.2. Why Architecture is important?
The primary goal of software architecture is to define the non-functional requirements of a system and define the environment. The detailed design is followed by a definition of how to deliver the functional behavior within the architectural rules. Architecture is important because it:
  • Controls complexity
  • Enforces best practices
  • Gives consistency and uniformity
  • Increases predictability
  • Enables re-use.
4.3. What is OOP?
OOP is a design philosophy. It stands for Object Oriented Programming. Object-Oriented Programming (OOP) uses a different set of programming languages than old procedural programming languages (C, Pascal, etc.). Everything in OOP is grouped as self sustainable "objects". Hence, you gain re-usability by means of four main object-oriented programming concepts.
In order to clearly understand the object orientation, let’s take your “hand” as an example. The “hand” is a class. Your body has two objects of type hand, named left hand and right hand. Their main functions are controlled/ managed by a set of electrical signals sent through your shoulders (through an interface). So the shoulder is an interface which your body uses to interact with your hands. The hand is a well architected class. The hand is being re-used to create the left hand and the right hand by slightly changing the properties of it.
4.4. What is an Object?
An object can be considered a "thing" that can perform a set of related activities. The set of activities that the object performs defines the object's behavior. For example, the hand can grip something or a Student (object) can give the name or address.
In pure OOP terms an object is an instance of a class.
4.5. What is a Class?
A class is simply a representation of a type of object. It is the blueprint/ plan/ template that describe the details of an object. A class is the blueprint from which the individual objects are created. Class is composed of three things: a name, attributes, and operations. Collapse | Copy Code
Collapse | Copy Code
public class Student
{
}
According to the sample given below we can say that the student object, named objectStudent, has created out of the Student class. Collapse | Copy Code
Collapse | Copy Code
Student objectStudent = new Student();
In real world, you'll often find many individual objects all of the same kind. As an example, there may be thousands of other bicycles in existence, all of the same make and model. Each bicycle has built from the same blueprint. In object-oriented terms, we say that the bicycle is an instance of the class of objects known as bicycles.
In the software world, though you may not have realized it, you have already used classes. For example, the TextBox control, you always used, is made out of the TextBox class, which defines its appearance and capabilities. Each time you drag a TextBox control, you are actually creating a new instance of the TextBox class.
4.6. How to identify and design a Class?
This is an art; each designer uses different techniques to identify classes. However according to Object Oriented Design Principles, there are five principles that you must follow when design a class,
  • SRP - The Single Responsibility Principle -
    A class should have one, and only one, reason to change.
  • OCP - The Open Closed Principle -
    You should be able to extend a classes behavior, without modifying it.
  • LSP - The Liskov Substitution Principle-
    Derived classes must be substitutable for their base classes.
  • DIP - The Dependency Inversion Principle-
    Depend on abstractions, not on concretions.
  • ISP - The Interface Segregation Principle-
    Make fine grained interfaces that are client specific.
For more information on design principles, please refer to Object Mentor.
Additionally to identify a class correctly, you need to identify the full list of leaf level functions/ operations of the system (granular level use cases of the system). Then you can proceed to group each function to form classes (classes will group same types of functions/ operations). However a well defined class must be a meaningful grouping of a set of functions and should support the re-usability while increasing expandability/ maintainability of the overall system.
In software world the concept of dividing and conquering is always recommended, if you start analyzing a full system at the start, you will find it harder to manage. So the better approach is to identify the module of the system first and then dig deep in to each module separately to seek out classes.
A software system may consist of many classes. But in any case, when you have many, it needs to be managed. Think of a big organization, with its work force exceeding several thousand employees (let’s take one employee as a one class). In order to manage such a work force, you need to have proper management policies in place. Same technique can be applies to manage classes of your software system as well. In order to manage the classes of a software system, and to reduce the complexity, the system designers use several techniques, which can be grouped under four main concepts named Encapsulation, Abstraction, Inheritance, and Polymorphism. These concepts are the four main gods of OOP world and in software term, they are called four main Object Oriented Programming (OOP) Concepts.
4.7. What is Encapsulation (or information hiding)?
The encapsulation is the inclusion within a program object of all the resources need for the object to function - basically, the methods and the data. In OOP the encapsulation is mainly achieved by creating classes, the classes expose public methods and properties. The class is kind of a container or capsule or a cell, which encapsulate the set of methods, attribute and properties to provide its indented functionalities to other classes. In that sense, encapsulation also allows a class to change its internal implementation without hurting the overall functioning of the system. That idea of encapsulation is to hide how a class does it but to allow requesting what to do.
In order to modularize/ define the functionality of a one class, that class can uses functions/ properties exposed by another class in many different ways. According to Object Oriented Programming there are several techniques, classes can use to link with each other and they are named association, aggregation, and composition.
There are several other ways that an encapsulation can be used, as an example we can take the usage of an interface. The interface can be used to hide the information of an implemented class. Collapse | Copy Code
Collapse | Copy Code
IStudent myStudent = new LocalStudent();
IStudent myStudent = new ForeignStudent();
According to the sample above (let’s assume that LocalStudent and ForeignStudent are implemented by the IStudent interface) we can see how LocalStudent and ForeignStudent are hiding their, localize implementing information through the IStudent interface.
4.8. What is Association?
Association is a (*a*) relationship between two classes. It allows one object instance to cause another to perform an action on its behalf. Association is the more general term that define the relationship between two classes, where as the aggregation and composition are relatively special. Collapse | Copy Code
Collapse | Copy Code
public class StudentRegistrar
{
   public StudentRegistrar ();
   {
       new RecordManager().Initialize();
   }
}
In this case we can say that there is an association between StudentRegistrar and RecordManager or there is a directional association from StudentRegistrar to RecordManager or StudentRegistrar use a (*Use*) RecordManager. Since a direction is explicitly specified, in this case the controller class is the StudentRegistrar.
To some beginners, association is a confusing concept. The troubles created not only by the association alone, but with two other OOP concepts, that is association, aggregation and composition. Every one understands association, before aggregation and composition are described. The aggregation or composition cannot be separately understood. If you understand the aggregation alone it will crack the definition given for association, and if you try to understand the composition alone it will always threaten the definition given for aggregation, all three concepts are closely related, hence must study together, by comparing one definition to another. Let’s explore all three and see whether we can understand the differences between these useful concepts.
4.9. What is the difference between Association, Aggregation and Composition?
Association is a (*a*) relationship between two classes, where one class use another. But aggregation describes a special type of an association. Aggregation is the (*the*) relationship between two classes. When object of one class has an (*has*) object of another, if second is a part of first (containment relationship) then we called that there is an aggregation between two classes. Unlike association, aggregation always insists a direction. Collapse | Copy Code
Collapse | Copy Code
public class University
{
   private Chancellor  universityChancellor = new Chancellor();
}
In this case I can say that University aggregate Chancellor or University has an (*has-a*) Chancellor. But even without a Chancellor a University can exists. But the Faculties cannot exist without the University, the life time of a Faculty (or Faculties) attached with the life time of the University . If University is disposed the Faculties will not exist. In that case we called that University is composed of Faculties. So that composition can be recognized as a special type of an aggregation.
Same way, as another example, you can say that, there is a composite relationship in-between a KeyValuePairCollection and a KeyValuePair. The two mutually depend on each other.
.Net and Java uses the Composite relation to define their Collections. I have seen Composition is being used in many other ways too. However the more important factor, that most people forget is the life time factor. The life time of the two classes that has bond with a composite relation mutually depend on each other. If you take the .net Collection to understand this, there you have the Collection Element define inside (it is an inner part, hence called it is composed of) the Collection, farcing the Element to get disposed with the Collection. If not, as an example, if you define the Collection and it’s Element to be independent, then the relationship would be more of a type Aggregation, than a Composition. So the point is, if you want to bind two classes with Composite relation, more accurate way is to have a one define inside the other class (making it a protected or private class). This way you are allowing the outer class to fulfill its purpose, while tying the lifetime of the inner class with the outer class.
So in summary, we can say that aggregation is a special kind of an association and composition is a special kind of an aggregation. (Association->Aggregation->Composition)
4.10. What is Abstraction and Generalization?
Abstraction is an emphasis on the idea, qualities and properties rather than the particulars (a suppression of detail). The importance of abstraction is derived from its ability to hide irrelevant details and from the use of names to reference objects. Abstraction is essential in the construction of programs. It places the emphasis on what an object is or does rather than how it is represented or how it works. Thus, it is the primary means of managing complexity in large programs.
While abstraction reduces complexity by hiding irrelevant detail, generalization reduces complexity by replacing multiple entities which perform similar functions with a single construct. Generalization is the broadening of application to encompass a larger domain of objects of the same or different type. Programming languages provide generalization through variables, parameterization, generics and polymorphism. It places the emphasis on the similarities between objects. Thus, it helps to manage complexity by collecting individuals into groups and providing a representative which can be used to specify any individual of the group.
Abstraction and generalization are often used together. Abstracts are generalized through parameterization to provide greater utility. In parameterization, one or more parts of an entity are replaced with a name which is new to the entity. The name is used as a parameter. When the parameterized abstract is invoked, it is invoked with a binding of the parameter to an argument.
4.11. What is an Abstract class?
Abstract classes, which declared with the abstract keyword, cannot be instantiated. It can only be used as a super-class for other classes that extend the abstract class. Abstract class is the concept and implementation gets completed when it is being realized by a subclass. In addition to this a class can inherit only from one abstract class (but a class may implement many interfaces) and must override all its abstract methods/ properties and may override virtual methods/ properties.
Abstract classes are ideal when implementing frameworks. As an example, let’s study the abstract class named LoggerBase below. Please carefully read the comments as it will help you to understand the reasoning behind this code. Collapse | Copy Code
Collapse | Copy Code
public abstract class LoggerBase
{
   /// <summary>
   /// field is private, so it intend to use inside the class only
   /// </summary>
   private log4net.ILog logger = null;

   /// <summary>
   /// protected, so it only visible for inherited class
   /// </summary>
   protected LoggerBase()
   {
       // The private object is created inside the constructor
       logger = log4net.LogManager.GetLogger(this.LogPrefix);
       // The additional initialization is done immediately after
       log4net.Config.DOMConfigurator.Configure();
   }

   /// <summary>
   /// When you define the property as abstract,
   /// it forces the inherited class to override the LogPrefix
   /// So, with the help of this technique the log can be made,
   /// inside the abstract class itself, irrespective of it origin.
   /// If you study carefully you will find a reason for not to have “set” method here.
   /// </summary>
   protected abstract System.Type LogPrefix
   {
       get;
   }

   /// <summary>
   /// Simple log method,
   /// which is only visible for inherited classes
   /// </summary>
   /// <param name="message"></param>
   protected void LogError(string message)
   {
       if (this.logger.IsErrorEnabled)
       {
           this.logger.Error(message);
       }
   }

   /// <summary>
   /// Public properties which exposes to inherited class
   /// and all other classes that have access to inherited class
   /// </summary>
   public bool IsThisLogError
   {
       get
       {
           return this.logger.IsErrorEnabled;
       }
   }
}
The idea of having this class as an abstract is to define a framework for exception logging. This class will allow all subclass to gain access to a common exception logging module and will facilitate to easily replace the logging library. By the time you define the LoggerBase, you wouldn’t have an idea about other modules of the system. But you do have a concept in mind and that is, if a class is going to log an exception, they have to inherit the LoggerBase. In other word the LoggerBase provide a framework for exception logging.
Let’s try to understand each line of the above code.
Like any other class, an abstract class can contain fields, hence I used a private field named logger declare the ILog interface of the famous log4net library. This will allow the Loggerbase class to control, what to use, for logging, hence, will allow changing the source logger library easily.
The access modifier of the constructor of the LoggerBase is protected. The public constructor has no use when the class is of type abstract. The abstract classes are not allowed to instantiate the class. So I went for the protected constructor.
The abstract property named LogPrefix is an important one. It enforces and guarantees to have a value for LogPrefix (LogPrefix uses to obtain the detail of the source class, which the exception has occurred) for every subclass, before they invoke a method to log an error.
The method named LogError is protected, hence exposed to all subclasses. You are not allowed or rather you cannot make it public, as any class, without inheriting the LoggerBase cannot use it meaningfully.
Let’s find out why the property named IsThisLogError is public. It may be important/ useful for other associated classes of an inherited class to know whether the associated member logs its errors or not.
Apart from these you can also have virtual methods defined in an abstract class. The virtual method may have its default implementation, where a subclass can override it when required.
All and all, the important factor here is that all OOP concepts should be used carefully with reasons, you should be able to logically explain, why you make a property a public or a field a private or a class an abstract. Additionally, when architecting frameworks, the OOP concepts can be used to forcefully guide the system to be developed in the way framework architect’s wanted it to be architected initially.
4.12. What is an Interface?
In summary the Interface separates the implementation and defines the structure, and this concept is very useful in cases where you need the implementation to be interchangeable. Apart from that an interface is very useful when the implementation changes frequently. Some say you should define all classes in terms of interfaces, but I think recommendation seems a bit extreme.
Interface can be used to define a generic template and then one or more abstract classes to define partial implementations of the interface. Interfaces just specify the method declaration (implicitly public and abstract) and can contain properties (which are also implicitly public and abstract). Interface definition begins with the keyword interface. An interface like that of an abstract class cannot be instantiated.
If a class that implements an interface does not define all the methods of the interface, then it must be declared abstract and the method definitions must be provided by the subclass that extends the abstract class. In addition to this an interfaces can inherit other interfaces.
The sample below will provide an interface for our LoggerBase abstract class. Collapse | Copy Code
Collapse | Copy Code
public interface ILogger
{
   bool IsThisLogError { get; }
}
4.13. What is the difference between a Class and an Interface?
In .Net/ C# a class can be defined to implement an interface and also it supports multiple implementations. When a class implements an interface, an object of such class can be encapsulated inside an interface.
If MyLogger is a class, which implements ILogger, there we can write Collapse | Copy Code
Collapse | Copy Code
ILogger log = new MyLogger();
A class and an interface are two different types (conceptually). Theoretically a class emphasis the idea of encapsulation, while an interface emphasis the idea of abstraction (by suppressing the details of the implementation). The two poses a clear separation from one to another. Therefore it is very difficult or rather impossible to have an effective meaningful comparison between the two, but it is very useful and also meaningful to have a comparison between an interface and an abstract class.
4.14. What is the difference between an Interface and an Abstract class?
There are quite a big difference between an interface and an abstract class, even though both look similar.
  • Interface definition begins with a keyword interface so it is of type interface
  • Abstract classes are declared with the abstract keyword so it is of type class
  • Interface has no implementation, but they have to be implemented.
  • Abstract class’s methods can have implementations and they have to be extended.
  • Interfaces can only have method declaration (implicitly public and abstract) and fields (implicitly public static)
  • Abstract class’s methods can’t have implementation only when declared abstract.
  • Interface can inherit more than one interfaces
  • Abstract class can implement more than one interfaces, but can inherit only one class
  • Abstract class must override all abstract method and may override virtual methods
  • Interface can be used when the implementation is changing
  • Abstract class can be used to provide some default behavior for a base class.
  • Interface makes implementation interchangeable
  • Interface increase security by hiding the implementation
  • Abstract class can be used when implementing framework
  • Abstract classes are an excellent way to create planned inheritance hierarchies and also to use as non-leaf classes in class hierarchies.
Abstract classes let you define some behaviors; they force your subclasses to provide others. For example, if you have an application framework, an abstract class can be used to provide the default implementation of the services and all mandatory modules such as event logging and message handling etc. This approach allows the developers to develop the application within the guided help provided by the framework.
However, in practice when you come across with some application-specific functionality that only your application can perform, such as startup and shutdown tasks etc. The abstract base class can declare virtual shutdown and startup methods. The base class knows that it needs those methods, but an abstract class lets your class admit that it doesn't know how to perform those actions; it only knows that it must initiate the actions. When it is time to start up, the abstract class can call the startup method. When the base class calls this method, it can execute the method defined by the child class.
4.15. What is Implicit and Explicit Interface Implementations?
As mentioned before .Net support multiple implementations, the concept of implicit and explicit implementation provide safe way to implement methods of multiple interfaces by hiding, exposing or preserving identities of each of interface methods, even when the method signatures are the same.
Let's consider the interfaces defined below. Collapse | Copy Code
Collapse | Copy Code
interface IDisposable
{
   void Dispose();
}  
Here you can see that the class Student has implicitly and explicitly implemented the method named Dispose() via Dispose and IDisposable.Dispose. Collapse | Copy Code
Collapse | Copy Code
class Student : IDisposable
{
   public void Dispose()
   {
       Console.WriteLine("Student.Dispose");
   }

   void IDisposable.Dispose()
   {
       Console.WriteLine("IDisposable.Dispose");
   }
}  
4.16. What is Inheritance?
Ability of a new class to be created, from an existing class by extending it, is called inheritance. Collapse | Copy Code
Collapse | Copy Code
public class Exception
{
}


public class IOException : Exception
{
}
According to the above example the new class (IOException), which is called the derived class or subclass, inherits the members of an existing class (Exception), which is called the base class or super-class. The class IOException can extend the functionality of the class Exception by adding new types and methods and by overriding existing ones.
Just like abstraction is closely related with generalization, the inheritance is closely related with specialization. It is important to discuss those two concepts together with generalization to better understand and to reduce the complexity.
One of the most important relationships among objects in the real world is specialization, which can be described as the “is-a” relationship. When we say that a dog is a mammal, we mean that the dog is a specialized kind of mammal. It has all the characteristics of any mammal (it bears live young, nurses with milk, has hair), but it specializes these characteristics to the familiar characteristics of canis domesticus. A cat is also a mammal. As such, we expect it to share certain characteristics with the dog that are generalized in Mammal, but to differ in those characteristics that are specialized in cats.
The specialization and generalization relationships are both reciprocal and hierarchical. Specialization is just the other side of the generalization coin: Mammal generalizes what is common between dogs and cats, and dogs and cats specialize mammals to their own specific subtypes.
Similarly, as an example you can say that both IOException and SecurityException are of type Exception. They have all characteristics and behaviors of an Exception, That mean the IOException is a specialized kind of Exception. A SecurityException is also an Exception. As such, we expect it to share certain characteristic with IOException that are generalized in Exception, but to differ in those characteristics that are specialized in SecurityExceptions. In other words, Exception generalizes the shared characteristics of both IOException and SecurityException, while IOException and SecurityException specialize with their characteristics and behaviors.
In OOP, the specialization relationship is implemented using the principle called inheritance. This is the most common and most natural and widely accepted way of implement this relationship.
4.17. What is Polymorphisms?
Polymorphisms is a generic term that means 'many shapes'. More precisely Polymorphisms means the ability to request that the same operations be performed by a wide range of different types of things.
At times, I used to think that understanding Object Oriented Programming concepts have made it difficult since they have grouped under four main concepts, while each concept is closely related with one another. Hence one has to be extremely careful to correctly understand each concept separately, while understanding the way each related with other concepts.
In OOP the polymorphisms is achieved by using many different techniques named method overloading, operator overloading and method overriding,
4.18. What is Method Overloading?
The method overloading is the ability to define several methods all with the same name. Collapse | Copy Code
Collapse | Copy Code
public class MyLogger
{
   public void LogError(Exception e)
   {
       // Implementation goes here
   }

   public bool LogError(Exception e, string message)
   {
       // Implementation goes here
   }
}
4.19. What is Operator Overloading?
The operator overloading (less commonly known as ad-hoc polymorphisms) is a specific case of polymorphisms in which some or all of operators like +, - or == are treated as polymorphic functions and as such have different behaviors depending on the types of its arguments. Collapse | Copy Code
Collapse | Copy Code
public class Complex
{
   private int real;
   public int Real
   { get { return real; } }

   private int imaginary;
   public int Imaginary
   { get { return imaginary; } }

   public Complex(int real, int imaginary)
   {
       this.real = real;
       this.imaginary = imaginary;
   }

   public static Complex operator +(Complex c1, Complex c2)
   {
       return new Complex(c1.Real + c2.Real, c1.Imaginary + c2.Imaginary);
   }
}
I above example I have overloaded the plus operator for adding two complex numbers. There the two properties named Real and Imaginary has been declared exposing only the required “get” method, while the object’s constructor is demanding for mandatory real and imaginary values with the user defined constructor of the class.
4.20. What is Method Overriding?
Method overriding is a language feature that allows a subclass to override a specific implementation of a method that is already provided by one of its super-classes.
A subclass can give its own definition of methods but need to have the same signature as the method in its super-class. This means that when overriding a method the subclass's method has to have the same name and parameter list as the super-class's overridden method. Collapse | Copy Code
Collapse | Copy Code
using System;
public class Complex
{
   private int real;
   public int Real
   { get { return real; } }

   private int imaginary;
   public int Imaginary
   { get { return imaginary; } }

   public Complex(int real, int imaginary)
   {
       this.real = real;
       this.imaginary = imaginary;
   }

   public static Complex operator +(Complex c1, Complex c2)
   {
       return new Complex(c1.Real + c2.Real, c1.Imaginary + c2.Imaginary);
   }

   public override string ToString()
   {
       return (String.Format("{0} + {1}i", real, imaginary));
   }
}
In above example I have extended the implementation of the sample Complex class given under operator overloading section. This class has one overridden method named “ToString”, which override the default implementation of the standard “ToString” method to support the correct string conversion of a complex number. Collapse | Copy Code
Collapse | Copy Code
Complex num1 = new Complex(5, 7);
Complex num2 = new Complex(3, 8);

// Add two Complex numbers using the
// overloaded plus operator
Complex sum = num1 + num2;

// Print the numbers and the sum
// using the overriden ToString method
Console.WriteLine("({0}) + ({1}) = {2}", num1, num2, sum);
Console.ReadLine();
4.21. What is a Use case?
A use case is a thing an actor perceives from the system. A use case maps actors with functions. Importantly, the actors need not be people. As an example a system can perform the role of an actor, when it communicate with another system.
In another angle a use case encodes a typical user interaction with the system. In particular, it:
  • Captures some user-visible function.

  • Achieves some concrete goal for the user.
A complete set of use cases largely defines the requirements for your system: everything the user can see, and would like to do. The below diagram contains a set of use cases that describes a simple login module of a gaming website.
4.22. What is a Class Diagram?
A class diagrams are widely used to describe the types of objects in a system and their relationships. Class diagrams model class structure and contents using design elements such as classes, packages and objects. Class diagrams describe three different perspectives when designing a system, conceptual, specification, and implementation. These perspectives become evident as the diagram is created and help solidify the design.
The Class diagrams, physical data models, along with the system overview diagram are in my opinion the most important diagrams that suite the current day rapid application development requirements.
UML Notations:
4.23. What is a Package Diagram?
Package diagrams are used to reflect the organization of packages and their elements. When used to represent class elements, package diagrams provide a visualization of the name-spaces. In my designs, I use the package diagrams to organize classes in to different modules of the system.
4.24. What is a Sequence Diagram?
A sequence diagrams model the flow of logic within a system in a visual manner, it enable both to document and validate your logic, and are used for both analysis and design purposes. Sequence diagrams are the most popular UML artifact for dynamic modeling, which focuses on identifying the behavior within your system.
4.25. What is two-tier architecture?
The two-tier architecture is refers to client/ server architectures as well, the term client/ server was first used in the 1980s in reference to personal computers (PCs) on a network. The actual client/ server model started gaining acceptance in the late 1980s, and later it was adapted to World Wide Web programming.
According to the modern days use of two-tier architecture the user interfaces (or with ASP.NET, all web pages) runs on the client and the database is stored on the server. The actual application logic can run on either the client or the server. So in this case the user interfaces are directly access the database. Those can also be non-interface processing engines, which provide solutions to other remote/ local systems. In either case, today the two-tier model is not as reputed as the three-tier model. The advantage of the two-tier design is its simplicity, but the simplicity comes with the cost of scalability. The newer three-tier architecture, which is more famous, introduces a middle tier for the application logic.
4.26. What is three-tier architecture?
The three tier software architecture (also known as three layer architectures) emerged in the 1990s to overcome the limitations of the two tier architecture. This architecture has aggressively customized and adopted by modern day system designer to web systems.
Three-tier is a client-server architecture in which the user interface, functional process logic, data storage and data access are developed and maintained as independent modules, some time on separate platforms. The term "three-tier" or "three-layer", as well as the concept of multi-tier architectures (often refers to as three-tier architecture), seems to have originated within Rational Software.
The 3-Tier architecture has the following three tiers.
  1. Presentation Tier or Web Server: User Interface, displaying/ accepting data/ input to/ from the user
  2. Application Logic/ Business Logic/ Transaction Tier or Application Server: Data validation, acceptability check before being added to the database and all other business/ application specific operations
  3. Data Tier or Database server: Simple reading and writing method to database or any other storage, connection, command, stored procedures etc
4.27. What is MVC architecture?
The Model-View-Controller (MVC) architecture separates the modeling of the domain, the presentation, and the actions based on user input into three separate classes.
Unfortunately, the popularity of this pattern has resulted in a number of faulty usages; each technology (Java, ASP.NET etc) has defined it in their own way making it difficult to understand. In particular, the term "controller" has been used to mean different things in different contexts. The definitions given bellow are the closes possible ones I found for ASP.NET version of MVC.
  1. Model: DataSet and typed DataSet (some times business object, object collection, XML etc) are the most common use of the model.
  2. View: The ASPX and ASCX files generally handle the responsibilities of the view.
  3. Controllers: The handling of events or the controlling is usually done in the code-behind class.
In a complex n-tier distributed system the MVC architecture place the vital role of organizing the presentation tier of the system.
4.28. What is SOA?
A service-oriented architecture is essentially a collection of services. These services communicate with each other. The communication can involve either simple data passing or it could involve two or more services coordinating some activity. Some means of connecting services to each other is needed.
The .Net technology introduces the SOA by mean of web services.
The SOA can be used as the concept to connect multiple systems to provide services. It has it's great share in the future of the IT world.
According to the imaginary diagram above, we can see how the Service Oriented Architecture is being used to provide a set of centralized services to the citizens of a country. The citizens are given a unique identifying card, where that card carries all personal information of each citizen. Each service centers such as shopping complex, hospital, station, and factory are equipped with a computer system where that system is connected to a central server, which is responsible of providing service to a city. As an example when a customer enter the shopping complex the regional computer system report it to the central server and obtain information about the customer before providing access to the premises. The system welcomes the customer. The customer finished the shopping and then by the time he leaves the shopping complex, he will be asked to go through a billing process, where the regional computer system will manage the process. The payment will be automatically handled with the input details obtain from the customer identifying card.
The regional system will report to the city (computer system of the city) while the city will report to the country (computer system of the country).
4.29. What is the Data Access Layer?
The data access layer (DAL), which is a key part of every n-tier system, is mainly consist of a simple set of code that does basic interactions with the database or any other storage device. These functionalities are often referred to as CRUD (Create, Retrieve, Update, and Delete).
The data access layer need to be generic, simple, quick and efficient as much as possible. It should not include complex application/ business logics.
I have seen systems with lengthy, complex store procedures (SP), which run through several cases before doing a simple retrieval. They contain not only most part of the business logic, but application logic and user interface logic as well. If SP is getting longer and complicated, then it is a good indication that you are burring your business logic inside the data access layer.
4.30. What is the Business Logic Layer?
I know for a fact that this is a question for most, but from the other hand by reading many articles I have become aware that not everyone agrees to what business logic actually is, and in many cases it's just the bridge in between the presentation layer and the data access layer with having nothing much, except taking from one and passing to the other. In some other cases, it is not even been well thought out, they just take the leftovers from the presentation layer and the data access layer then put them in another layer which automatically is called the business logic layer. However there are no god said things that cannot be changed in software world. You can change as and when you feel comfortable that the method you apply is flexible enough to support the growth of your system. There are many great ways, but be careful when selecting them, they can over complicating the simple system. It is a balance one needs to find with their experience.
As a general advice when you define business entities, you must decide how to map the data in your tables to correctly defined business entities. The business entities should meaningfully define considering various types of requirements and functioning of your system. It is recommended to identify the business entities to encapsulate the functional/ UI (User Interface) requirements of your application, rather than define a separate business entity for each table of your database. For example, if you want to combine data from couple of table to build a UI (User Interface) control (Web Control), implement that function in the Business Logic Layer with a business object that uses couple of data object to support with your complex business requirement.
4.31. What is Gang of Four (GoF) Design Patterns?
The Gang of Four (GoF) patterns are generally considered the foundation for all other patterns. They are categorized in three groups: Creational, Structural, and Behavioral. Here you will find information on these important patterns.
Creational Patterns

  • Abstract Factory Creates an instance of several families of classes
  • Builder Separates object construction from its representation
  • Factory Method Creates an instance of several derived classes
  • Prototype A fully initialized instance to be copied or cloned
  • Singleton A class of which only a single instance can exist
Structural Patterns

  • Adapter Match interfaces of different classes
  • Bridge Separates an object’s interface from its implementation
  • Composite A tree structure of simple and composite objects
  • Decorator Add responsibilities to objects dynamically
  • Facade A single class that represents an entire subsystem
  • Flyweight A fine-grained instance used for efficient sharing
  • Proxy An object representing another object
Behavioral Patterns

  • Chain of Resp. A way of passing a request between a chain of objects
  • Command Encapsulate a command request as an object
  • Interpreter A way to include language elements in a program
  • Iterator Sequentially access the elements of a collection
  • Mediator Defines simplified communication between classes
  • Memento Capture and restore an object's internal state
  • Observer A way of notifying change to a number of classes
  • State Alter an object's behavior when its state changes
  • Strategy Encapsulates an algorithm inside a class
  • Template Method Defer the exact steps of an algorithm to a subclass
  • Visitor Defines a new operation to a class without change
4.32. What is the difference between Abstract Factory and Builder design patterns?
The two design patterns are fundamentally different. However, when you learn them for the first time, you will see a confusing similarity. So that it will make harder for you to understand them. But if you continue to study eventually, you will get afraid of design patterns too. It is like infant phobia, once you get afraid at your early age, it stays with you forever. So the result would be that you never look back at design patterns again. Let me see whether I can solve this brain teaser for you.
In the image below, you have both design pattern listed in. I am trying to compare the two one on one to identify the similarities. If you observe the figure carefully, you will see an easily understandable color pattern (same color is used to mark the classes that are of similar kind).
Please follow up with the numbers in the image when reading the listing below.
Mark #1: Both patterns have used a generic class as the entry-class. The only difference is the name of the class. One pattern has named it as “Client”, while the other named it as “Director”.
Mark
#2: Here again the difference is the class name. It is “AbstractFactory” for one and “Builder” for the other. Additionally both classes are of type abstract.
Mark
#3: Once again both patterns have defined two generic (WindowsFactory & ConcreteBuilder) classes. They both have created by inheriting their respective abstract class.
Mark
#4: Finally, both seem to produce some kind of a generic output.
Now, where are we? Aren’t they looking almost identical? So then why are we having two different patterns here?
Let’s compare the two again side by side for one last time, but this time, focusing on the differences.
  • Abstract Factory: Emphasizes a family of product objects (either simple or complex)
  • Builder: Focuses on constructing a complex object step by step

  • Abstract Factory: Focus on *what* is made
  • Builder: Focus on *how* it is made

  • Abstract Factory: Focus on defining many different types of *factories* to build many *products*, and it is not a one builder for just one product
  • Builder: Focus on building a one complex but one single *product*

  • Abstract Factory: Defers the choice of what concrete type of object to make until run time
  • Builder: Hide the logic/ operation of how to compile that complex object

  • Abstract Factory: *Every* method call creates and returns different objects
  • Builder: Only the *last* method call returns the object, while other calls partially build the object
Sometimes creational patterns are complementary: So you can join one or many patterns when you design your system. As an example builder can use one of the other patterns to implement which components get built or in another case Abstract Factory, Builder, and Prototype can use Singleton in their implementations. So the conclusion would be that the two design patterns exist to resolve two type of business problems, so even though they look similar, they are not.
I hope that this shed some light to resolve the puzzle. If you still don’t understand it, then this time it is not you, it has to be me and it is since that I don’t know how to explain it.
5. What is the Conclusion?
I don't think, that it is realistic trying to make a programming language be everything to everybody. The language becomes bloated, hard to learn, and hard to read if everything plus the kitchen sink is thrown in. In another word every language has their limitations. As system architect and designer we should be able to fully and more importantly correctly (this also mean that you shouldn’t use a ballistic missile to kill a fly or hire FBI to catch the fly) utilize the available tools and features to build usable, sustainable, maintainable and also very importantly expandable software systems, that fully utilize the feature of the language to bring a competitively advance system to their customers. In order to do it, the foundation of a system places a vital role. The design or the architecture of a software system is the foundation. It hold the system together, hence designing a system properly (this never mean an *over* desinging) is the key to the success. When you talk about designing a software system, the correct handling of OOP concept is very important. I have made the above article richer with idea but still kept it short so that one can learn/ remind all of important concept at a glance. Hope you all will enjoy reading it.
Finally, after reading all these, one may argue with me saying that anybody can write all these concept definitions but do I know how/ when to apply them in real world systems. So for them to see these concepts being applied in real world systems, please check the source code of the latest of my open-source project name Rocket Framework.
Note: For newbies Rocket Framework is going to be little too advance but check it, use it and review it if you have any questions/ criticisms around my design don't hesitate to shoot them here or there..
What is Polymorphism?

Polymorphism means one name many forms.

Polymorphism means one object behaving as multiple forms.
One function behaves different forms.
In other words, "Many forms of a single object is called Polymorphism."

Real World Example of Polymorphism:
Example-1: 
A Teacher behaves to student.
A Teacher behaves to his/her seniors.
Here teacher is an object but attitude is different in different situation.
Example-2: 
Person behaves SON in house at the same time that person behaves EMPLOYEE in office.
Example-3: 
Your mobile phone, one name but many forms

  • As phone
  • As camera
  • As mp3 player
  • As radio
With polymorphism, the same method or property can perform different actions depending on the run-time type of the instance that invokes it. 

There are two types of polymorphism:-

1)  Static or Compile time Polymorphism
2)  Dynamic or Runtime Polymorphism.

Static or Compile time Polymorphism:-
   In Static Polymorphism the decision is made at compile time.
     ∙   Which method is to be called is decided at compile-time only ?
     ∙   Method overloading is an example of this.
   Compile time polymorphism is method overloading, where the compiler knows which             overloaded method it is going to call.

Method overloading is a concept where a class can have more than one method with same name and different parameters. 
Compiler checks the type and number of parameters passed on to the method and decides which method to call at the compile time and it will give an error if there are no method that matches the method signature of the method that is called at the compile time.
      
      Example:-

              
namespace MethodOverloadingByManishAgrahari
{
    class Program
    {
        public class TestOverloading
        {

            public void Add(string a1, string a2)    
            {
                Console.WriteLine("Adding Two String :" + a1 + a2);
            }

            public void Add(int a1, int a2)
            {
                Console.WriteLine("Adding Two Integer :" +  a1 + a2);
            }

        }

        static void Main(string[] args)
        {
            TestOverloading obj = new TestOverloading();

            obj.Add("Manish " , "Agrahari");

            obj.Add(5, 10);

            Console.ReadLine();
        }
    }
}





 Dynamic or Runtime Polymorphism:-

Run-time polymorphism is achieved by method overriding.

Method Overriding allows us to have methods in the base and derived classes with same name and same parameters.

By runtime polymorphism we can point to any derived class from the object of the base class at runtime that shows the ability of runtime binding.

Through the reference variable of a base class, the determination of the method to be called is based on the object being referred to by reference variable.

Compiler would not be aware of the method is available for overriding the functionality or not. So compiler would not give any error at compile time. At runtime it will be decided which method to call and if there is no method at runtime it will give an error

See Following Example:-
namespace PolymorphismByManishAgrahari
{
    class Program
    {
        public class Base
        {

            public virtual void Show()
            {
                Console.WriteLine("Show From Base Class.");
            }
        }

        public class Derived : Base
        {
            public override void Show()
            {
                Console.WriteLine("Show From Derived Class.");
            }
        }
        static void Main(string[] args)
        {
            Base objBase;
            objBase = new Base();
            objBase.Show();//    Output ----> Show From Base Class.

            objBase = new Derived();
            objBase.Show();//Output--> Show From Derived Class.

            Console.ReadLine();
        }
    }
} 



Compiler demands virtual Show()  method and it compiles successfully. The right version of Show()  method cannot be determined until run-time since only at that time Base objBase is initialized as Derived.

Virtual Keyword:-
According to MSDN, “The virtual keyword is used to modify a method, property, indexer or event declaration, and allow it to be overridden in a derived class.”
Virtual Method:-
Virtual method is a method whose behavior can be overridden in derived class.
Virtual method allows declare a method in base class that can be redefined in each derived class.
When a virtual method is invoked, the run-time type of the object is checked for an overriding member. The overriding member in the most derived class is called, which might be the original member, if no derived class has overridden the member.
  • By default, methods are non-virtual. You cannot override a non-virtual method.

  • You cannot use the virtual modifier with the static, abstract, private or override modifiers.

  • Virtual properties behave like abstract methods, except for the differences in declaration and invocation syntax.

  • It is an error to use the virtual modifier on a static property.

  • A virtual inherited property can be overridden in a derived class by including a property declaration that uses the override modifier.


 Virtual method solves the following problem:-
In OOP when a derived class inherits from a base class, an object of the derived class may be referred to (or cast) as either being the base class type or the derived class type. If there are base class methods overridden by the derived class, the method call behavior is ambiguous.
In C#, polymorphism is explicit - you must have a virtual (or abstract) modifier on the base class method (member) and an override on the derived class method, which you probably already know.  
If you don't put a modifier on a base class method, polymorphism can't ever happen.  If you then add a non-modified method to the derived class with the same signature as the non-modified base class method, the compiler will generate a Warning message. 
See Following Example:-
namespace PolymorphismByManishAgrahari
{
    class Program
    {
        public class Base
        {

            public void Show()
            {
                Console.WriteLine("Show From Base Class.");
            }
        }

        public class Derived : Base
        {
            //Following line will Give an Warning
            /*
             'PolymorphismByManishAgrahari.Program.Derived.Show()'
  hides  inherited member
             'PolymorphismByManishAgrahari.Program.Base.Show()'.
              Use the new keyword if hiding was intended.  
            */
            public void Show()
            {
                Console.WriteLine("Show From Derived Class.");
            }
        }
        static void Main(string[] args)
        {
            Base objBase = new Base();
            objBase.Show();//    Output ----> Show From Base Class.

            Derived objDerived = new Derived();
            objDerived.Show();//Output--> Show From Derived Class.


            Base objBaseRefToDerived = new Derived();
            objBaseRefToDerived.Show();//Output--> Show From Base Class.

            Console.ReadLine();
        }
    }
}


It means that you are hiding (re-defining) the base class method. 
In other languages, take Java for instance, you have what is called "implicit" polymorphism where just putting the method in the derived class with the same signature as a base class method will enable polymorphism. 
In Java, all methods of a class are virtual by default unless the developer decides to use the final keyword thus preventing subclasses from overriding that method. In contrast C# adopts the strategy used by C++ where the developer has to use the virtual keyword for subclasses to override the method. Thus all methods in C# are non virtual by default.


The C# approach is more explicit for the purpose of making the code safer in versioning scenarios.  i.e. You build your code based on a 3rd party library and use meaningful, but common, method names.  The 3rd party library upgrades, using the same common method name.  With implicit polymorphism the code would break, but with C# you would receive a compiler warning so you can double check to see if polymorphism was something you wanted to do.



Difference between Method Overriding and Method hiding
Method overriding allows a subclass to provide a specific implementation of a method that is already provided by base class. The implementation in the subclass overrides (replaces) the implementation in the base class.
The important thing to remember about overriding is that the method that is doing the overriding is related to the method in the base class.
When a virtual method is called on a reference, the actual type of the object to which the reference refers is used to determine which method implementation should be used. When a method of a base class is overridden in a derived class (subclass), the version defined in the derived class is used. This is so even should the calling application be unaware that the object is an instance of the derived class.
namespace PolymorphismByManishAgrahari
{
    class Program
{
        public class Base
        {
     
            public virtual void Show()
            {
                Console.WriteLine("Show From Base Class.");
            }
        }

        public class Derived : Base
        {
//the keyword "override" change the base class method.
            public override void Show()
            {
                Console.WriteLine("Show From Derived Class.");
            }
        }
        static void Main(string[] args)
        {
            Base objBaseRefToDerived  = new Derived();
            objBaseRefToDerived .Show();//Output--> Show From Derived Class.
          
            Console.ReadLine();
        }
    }
}
Output--> Show From Derived Class
Method hiding does not have a relationship between the methods in the base class and derived class. The method in the derived class hides the method in the base class.
namespace PolymorphismByManishAgrahari
{
    class Program
    {
        public class Base
        {

            public virtual void Show()
            {
                Console.WriteLine("Show From Base Class.");
            }
        }

        public class Derived : Base
        {

            public new void Show()
            {
                Console.WriteLine("Show From Derived Class.");
            }
        }
        static void Main(string[] args)
        {
            Base objBaseRefToDerived  = new Derived();
            objBaseRefToDerived .Show();//Output--> Show From Base Class.
          
            Console.ReadLine();
        }
    }
}
Output is: Show From Base Class.
In the preceding example, Derived.Show will be called; because, it overrides Base.Show

  • The c# language specification states that  "You cannot override a non-virtual method." see following example:-
namespace PolymorphismByManishAgrahari
{
    class Program
    {
        public class Base
        {

            public void Show()
            {
                Console.WriteLine("This is Base Class.");
            }
        }

        public class Derived : Base
        {
            //Following Line will give error.
            /*
             Error:- 'PolymorphismByManishAgrahari.Program.Derived.Show()'
cannot override inherited member  'PolymorphismByManishAgrahari.Program.Base.Show()'
             * because it is not marked virtual, abstract, or override
          */
            public override void Show()
            {

                Console.WriteLine("This is Derived Class.");
            }
        }
        static void Main(string[] args)
        {
            Base objBase = new Base();
            objBase.Show();//    Output ----> This is Base Class.

            Derived objDerived = new Derived();
            objDerived.Show();//Output--> This is Derived Class.

            Base objBaseRefToDerived = new Derived();
            objBaseRefToDerived.Show();//Output--> This is Base Class.

            Console.ReadLine();
        }
    }
}
Error:- 'PolymorphismByManishAgrahari.Program.Derived.Show()' cannot override inherited member 'PolymorphismByManishAgrahari.Program.Base.Show()' because it is not marked virtual, abstract, or override

Sealed keyword:-
Sealed keyword can be used to stop method overriding in a derived classes.
By default, all methods a sealed, which means you can't override them, so that "sealed" keyword is redundant in this case and compiler will show you error when you'll try to make sealed already sealed method. But if your method was marked as virtual in a base class, by overriding and marking this method with "sealed" will prevent method overriding in derived classes.
See following example:-
namespace PolymorphismByManishAgrahari
{
    class Program
    {
        public class Base
        {

public sealed void Show()//This Line will give an error - "cannot        
{                      //be sealed because it is not an override"

             Console.WriteLine("This is Base Class.");
            }
        }

        public class Derived : Base
        {
            public void Show()
            {

                Console.WriteLine("This is Derived Class.");
            }
        }
        static void Main(string[] args)
        {
            Base objBaseReference = new Derived();
            objBaseReference.Show();// Output ---------> This is Base Class.

            Console.ReadLine();
        }
    }
}

Error:-
'PolymorphismByManishAgrahari.Program.Base.Show()' cannot be sealed because it is not an override

To Remove Error from Above Program use following:-
namespace PolymorphismByManishAgrahari
{
    class Program
    {
        public class Base
        {

            public virtual void Show()    
            {                     
                Console.WriteLine("This is Base Class.");
            }
        }

        public class Derived : Base
        {
            public override sealed void Show()
            {

                Console.WriteLine("This is Derived Class.");
            }
        }

        static void Main(string[] args)
        {
            Base objBaseReference = new Derived();
            objBaseReference.Show();// Output ---> This is Derived Class.

         Console.ReadLine();
        }
    }
}
Output ---> This is Derived Class.

Summary:-
  1. It is not compulsory to mark the derived/child class function with override keyword while base/parent class contains a virtual method
  2. Virtual methods allow subclasses to provide their own implementation of that method using the override keyword
  3. Virtual methods can't be declared as private.
  4. You are not required to declare a method as virtual. But, if you don't, and you derive from the class, and your derived class has a method by the same name and signature, you'll get a warning that you are hiding a parent's method
  5. A virtual property or method has an implementation in the base class, and can be overridden in the derived classes.
  6. We will get a warning if we won't use Virtual/New keyword.
  7. Instead of Virtual we can use New Keyword 

Comments

Popular posts from this blog

SQL SERVER noteS......ip notes....

page life cycle in asp.net.......

ASP.Net Page Life Cycle