Specializations

Showing posts with label OOPS. Show all posts
Showing posts with label OOPS. Show all posts

Tuesday, March 4, 2014

oops FAQs

1. What is object-oriented programming (OOP)?
OOP is a technique to develop logical modules, such as classes that contain properties, methods, fields, and events. An object is created in the program to represent a class. Therefore, an object encapsulates all the features, such as data and behavior that are associated to a class. OOP allows developers to develop modular programs and assemble them as software. Objects are used to access data and behaviors of different software modules, such as classes, namespaces, and sharable assemblies. .NET Framework supports only OOP languages, such as Visual Basic .NET, Visual C#, and Visual C++.
2. What is a class?
A class describes all the attributes of objects, as well as the methods that implement the behavior of member objects. It is a comprehensive data type, which represents a blue print of objects. It is a template of object.

A class can be defined as the primary building block of OOP. It also serves as a template that describes the properties, state, and behaviors common to a particular group of objects.

A class contains data and behavior of an entity. For example, the aircraft class can contain data, such as model number, category, and color and behavior, such as duration of flight, speed, and number of passengers. A class inherits the data members and behaviors of other classes by extending from them.
3. What is an object?
They are instance of classes. It is a basic unit of a system. An object is an entity that has attributes, behavior, and identity. Attributes and behavior of an object are defined by the class definition.
4. What is the relationship between a class and an object?
A class acts as a blue-print that defines the properties, states, and behaviors that are common to a number of objects. An object is an instance of the class. For example, you have a class called Vehicle and Car is the object of that class. You can create any number of objects for the class named Vehicle, such as Van, Truck, and Auto.

The new operator is used to create an object of a class. When an object of a class is instantiated, the system allocates memory for every data member that is present in the class.
5. Explain the basic features of OOPs.
The following are the four basic features of OOP:
  • Abstraction - Refers to the process of exposing only the relevant and essential data to the users without showing unnecessary information.
  • Polymorphism - Allows you to use an entity in multiple forms.
  • Encapsulation - Prevents the data from unwanted access by binding of code and data in a single unit called object.
  • Inheritance - Promotes the reusability of code and eliminates the use of redundant code. It is the property through which a child class obtains all the features defined in its parent class. When a class inherits the common properties of another class, the class inheriting the properties is called a derived class and the class that allows inheritance of its common properties is called a base class.
6. What is the difference between arrays and collection?
Array:
  1. You need to specify the size of an array at the time of its declaration. It cannot be resized dynamically.
  2. The members of an array should be of the same data type.

Collection:
  1. The size of a collection can be adjusted dynamically, as per the user's requirement. It does not have fixed size.
  2. Collection can have elements of different types.

7. What are collections and generics?
A collection can be defined as a group of related items that can be referred to as a single unit. TheSystem.Collections namespace provides you with many classes and interfaces. Some of them are -ArrayList, List, Stack, ICollection, IEnumerable, and IDictionary. Generics provide the type-safety to your class at the compile time. While creating a data structure, you never need to specify the data type at the time of declaration. The System.Collections.Generic namespace contains all the generic collections.
8. How can you prevent your class to be inherited further?
You can prevent a class from being inherited further by defining it with the sealed keyword.
9. What is the index value of the first element in an array?
In an array, the index value of the first element is 0 (zero).
10. Can you specify the accessibility modifier for methods inside the interface?
All the methods inside an interface are always public, by default. You cannot specify any other access modifier for them.
11. Is it possible for a class to inherit the constructor of its base class?
No, a class cannot inherit the constructor of its base class.
12. How is method overriding different from method overloading?
Overriding involves the creation of two or more methods with the same name and same signature in different classes (one of them should be parent class and other should be child).

Overloading is a concept of using a method at different places with same name and different signatures within the same class.

13. What is the difference between a class and a structure?
Class:
  1. A class is a reference type.
  2. While instantiating a class, CLR allocates memory for its instance in heap.
  3. Classes support inheritance.
  4. Variables of a class can be assigned as null.
  5. Class can contain constructor/destructor.

Structure:
  1. A structure is a value type.
  2. In structure, memory is allocated on stack.
  3. Structures do not support inheritance.
  4. Structure members cannot have null values.
  5. Structure does not require constructor/destructor and members can be initialiazed automatically.
14. What are similarities between a class and a structure.
Structures and classes are the two most important data structures that are used by programmers to build modular programs by using OOP languages, such as Visual Basic .NET, and Visual C#. The following are some of the similarities between a class and a structure:
  • Access specifiers, such as public, private, and protected, are identically used in structures and classes to restrict the access of their data and methods outside their body.
  • The access level for class members and struct members, including nested classes and structs, is private by default. Private nested types are not accessible from outside the containing type.
  • Both can have constructors, methods, properties, fields, constants, enumerations, events, and event handlers.
  • Both structures and classes can implement interfaces to use multiple-inheritance in code.
  • Both structures and classes can have constructors with parameter.
  • Both structures and classes can have delegates and events.
15. What is a multicast delegate?
Each delegate object holds reference to a single method. However, it is possible for a delegate object to hold references of and invoke multiple methods. Such delegate objects are called multicast delegates or combinable delegates.
16. Can you declare an overridden method to be static if the original method is not static?
No. Two virtual methods must have the same signature.
17. Why is the virtual keyword used in code?
The virtual keyword is used while defining a class to specify that the methods and the properties of that class can be overridden in derived classes.
18. Can you allow a class to be inherited, but prevent a method from being overridden in C#?
Yes. Just declare the class public and make the method sealed.

19. Define enumeration?
Enumeration is defined as a value type that consists of a set of named values. These values are constants and are called enumerators. An enumeration type is declared using the enum keyword. Each enumerator in an enumeration is associated with an underlying type that is set, by default, on the enumerator. The following is an example that creates an enumeration to store different varieties of fruits:

enum Fruits {Mango, Apple, orange, Guava}; 

In the preceding example, an enumeration Fruits is created, where number 0 is associated with Mango, number 1 with Apple, number 2 with Orange, and number 3 with Guava. You can access the enumerators of an enumeration by these values.
20. In which namespace, all .NET collection classes are contained?
The System.Collections namespace contains all the collection classes.
21. Is it a good practice to handle exceptions in code?
Yes, you must handle exceptions in code so that you can deal with any unexpected situations that occur when a program is running. For example, dividing a number by zero or passing a string value to a variable that holds an integer value would result in an exception.
22. Explain the concept of constructor?
Constructor is a special method of a class, which is called automatically when the instance of a class is created. It is created with the same name as the class and initializes all class members, whenever you access the class. The main features of a constructor are as follows:
  • Constructors do not have any return type
  • Constructors are always public
  • It is not mandatory to declare a constructor; it is invoked automatically by .NET Framework.
23. Can you inherit private members of a class?
No, you cannot inherit private members of a class because private members are accessible only to that class and not outside that class.
24. Does .NET support multiple inheritance?
.NET does not support multiple inheritance directly because in .NET, a class cannot inherit from more than one class. .NET supports multiple inheritance through interfaces.

25. How has exception handling changed in .NET Framework 4.0?
In .NET 4.0, a new namespace, System.Runtime.ExceptionServices, has been introduced which contains the following classes for handling exceptions in a better and advanced manner:
  • HandleProcessCorruptedStateExceptionsAttribute Class - Enables managed code to handle the corrupted state exceptions that occur in an operating system. These exceptions cannot be caught by specifying the try...catch block. To handle such exceptions, you can apply this attribute to the method that is assigned to handle these exceptions.
  • FirstChanceExceptionEventArgs Class - Generates an event whenever a managed exception first occurs in your code, before the common language runtime begins searching for event handlers.
26. What is a delegate?
A delegate is similar to a class that is used for storing the reference to a method and invoking that method at runtime, as required. A delegate can hold the reference of only those methods whose signatures are same as that of the delegate. Some of the examples of delegates are type-safe functions, pointers, or callbacks.
27. What is the syntax to inherit from a class in C#?
When a class is derived from another class, then the members of the base class become the members of the derived class. The access modifier used while accessing members of the base class specifies the access status of the base class members inside the derived class.

The syntax to inherit a class from another class in C# is as follows:
class MyNewClass : MyBaseclass
28. State the features of an interface.
An interface is a template that contains only the signature of methods. The signature of a method consists of the numbers of parameters, the type of parameter (value, reference, or output), and the order of parameters. An interface has no implementation on its own because it contains only the definition of methods without any method body. An interface is defined using the interface keyword. Moreover, you cannot instantiate an interface. The various features of an interface are as follows:
  • An interface is used to implement multiple inheritance in code. This feature of an interface is quite different from that of abstract classes because a class cannot derive the features of more than one class but can easily implement multiple interfaces.
  • It defines a specific set of methods and their arguments.
  • Variables in interface must be declared as public, static, and final while methods must be publicand abstract.
  • A class implementing an interface must implement all of its methods.
  • An interface can derive from more than one interface.
29. Can you use the 'throws' clause to raise an exception?
No, the throws clause cannot be used to raise an exception. The throw statement signals the occurrence of an exception during the execution of a program. When the program encounters a throw statement, the method terminates and returns the error to the calling method.
30. Define an array.
An array is defined as a homogeneous collection of elements, stored at contiguous memory locations, which can be referred by the same variable name. All the elements of an array variable can be accessed by index values. An Index value specifies the position of a particular element in an array variable.


31. What are methods?
Methods are the building blocks of a class, in which they are linked together to share and process data to produce the result. In other words, a method is a block of code that contains a series of statements and represents the behavior of a class. While declaring a method you need to specify the access specifier, the return value, the name of the method, and the method parameters. All these combined together is called the signature of the method.
32. What is a namespace?
Namespace is considered as a container that contains functionally related group of classes and other types.
33. Do events have return type?
No, events do not have return type.
34. What is the function of the Try-Catch-Finally block?
The try block encloses those statements that can cause exception and the catch block handles the exception, if it occurs. Catch block contains the statements that have to be executed, when an exception occurs. Thefinally block always executes, irrespective of the fact whether or not an exception has occurred. The finallyblock is generally used to perform the cleanup process. If any exception occurs in the try block, the program control directly transfers to its corresponding catch block and later to the finally block. If no exception occurs inside the try block, then the program control transfers directly to the finally block.
35. How can you prevent a class from overriding in C# and Visual Basic?
You can prevent a class from overriding in C# by using the sealed keyword; whereas, the NotInheritablekeyword is used to prevent a class from overriding in Visual Basic.
36. What are abstract classes? What are the distinct characteristics of an abstract class?
An abstract class is a class that cannot be instantiated and is always used as a base class.
The following are the characteristics of an abstract class:
  • You cannot instantiate an abstract class directly. This implies that you cannot create an object of the abstract class; it must be inherited.
  • You can have abstract as well as non-abstract members in an abstract class.
  • You must declare at least one abstract method in the abstract class.
  • An abstract class is always public.
  • An abstract class is declared using the abstract keyword.

The basic purpose of an abstract class is to provide a common definition of the base class that multiple derived classes can share.

37. Give a brief description of properties in C# and the advantages that are obtained by using them in programs.
In C#, a property is a way to expose an internal data element of a class in a simple and intuitive manner. In other words, it is a simple extension of data fields. You can create a property by defining an externally available name and then writing the set and get property accessors. The get property accessor is used to return theproperty value. The set property accessor is used to assign a new value to the property.
38. Explain different types of inheritance.
Inheritance in OOP is of four types:
  • Single inheritance - Contains one base class and one derived class
  • Hierarchical inheritance - Contains one base class and multiple derived classes of the same base class
  • Multilevel inheritance - Contains a class derived from a derived class
  • Multiple inheritance - Contains several base classes and a derived class
All .NET languages supports single, hierarchical, and multilevel inheritance. They do not support multiple inheritance because in these languages, a derived class cannot have more than one base class. However, you can implement multiple inheritance in.NET through interfaces.
39. You have defined a destructor in a class that you have developed by using the C# programming language, but the destructor never executed. Why did the destructor not execute?
The runtime environment automatically invokes the destructor of a class to release the resources that are occupied by variables and methods of an object. However, in C#, programmers cannot control the timing for invoking destructors, as Garbage Collector is only responsible for releasing the resources used by an object. Garbage Collector automatically gets information about unreferenced objects from .NET's runtime environment and then invokes the Finalize() method.

Although, it is not preferable to force Garbage Collector to perform garbage collection and retrieve all inaccessible memory, programmers can use the Collect() method of the Garbage Collector class to forcefully execute Garbage Collector.
40. What is a hashtable?
Hashtable is a data structure that implements the IDictionary interface. It is used to store multiple items and each of these items is associated with a unique string key. Each item can be accessed using the key associated with it. In short, hashtable is an object holding the key-value pairs.
41. Can users define their own exceptions in code?
Yes, customized exceptions can be defined in code by deriving from the System.Exception class.
42. Is it possible to execute two catch blocks?
You are allowed to include more than one catch block in your program; however, it is not possible to execute them in one go. Whenever, an exception occurs in your program, the correct catch block is executed and the control goes to the finally block.



43. What do you mean by data encapsulation?
Data encapsulation is a concept of binding data and code in single unit called object and hiding all the implementation details of a class from the user. It prevents unauthorized access of data and restricts the user to use the necessary data only.
44. What is the difference between procedural and object-oriented programming?
Procedural programming is based upon the modular approach in which the larger programs are broken into procedures. Each procedure is a set of instructions that are executed one after another. On the other hand, OOP is based upon objects. An object consists of various elements, such as methods and variables.

Access modifiers are not used in procedural programming, which implies that the entire data can be accessed freely anywhere in the program. In OOP, you can specify the scope of a particular data by using access modifiers - public, private, internal, protected, and protected internal.
45. Explain the concept of destructor?
A destructor is a special method for a class and is invoked automatically when an object is finally destroyed. The name of the destructor is also same as that of the class but is followed by a prefix tilde (~).

A destructor is used to free the dynamic allocated memory and release the resources. You can, however, implement a custom method that allows you to control object destruction by calling the destructor.

The main features of a destructor are as follows:
  • Destructors do not have any return type
  • Similar to constructors, destructors are also always public
  • Destructors cannot be overloaded.
46. Can you declare a private class in a namespace?
The classes in a namespace are internal, by default. However, you can explicitly declare them as public only and not as private, protected, or protected internal. The nested classes can be declared as private,protected, or protected internal.
47. A structure in C# can implement one or more interfaces. Is it true or false?
Yes, it is true. Like classes, in C#, structures can implement one or more interfaces.
48. What is a static constructor?
Static constructors are introduced with C# to initialize the static data of a class. CLR calls the static constructor before the first instance is created.

The static constructor has the following features:
  • No access specifier is required to define it.
  • You cannot pass parameters in static constructor.
  • A class can have only one static constructor.
  • It can access only static members of the class.
  • It is invoked only once, when the program execution begins.

49. What are the different ways a method can be overloaded?
The different ways to overload a method are given as follows:
  • By changing the number of parameters used
  • By changing the order of parameters
  • By using different data types for the parameters
50. Differentiate between an abstract class and an interface.
Abstract Class:
  1. A class can extend only one abstract class
  2. The members of abstract class can be private as well as protected.
  3. Abstract classes should have subclasses
  4. Any class can extend an abstract class.
  5. Methods in abstract class can be abstract as well as concrete.
  6. There can be a constructor for abstract class.
  7. The class extending the abstract class may or may not implement any of its method.
  8. An abstract class can implement methods.

Interface
  1. A class can implement several interfaces
  2. An interface can only have public members.
  3. Interfaces must have implementations by classes
  4. Only an interface can extend another interface.
  5. All methods in an interface should be abstract
  6. Interface does not have constructor.
  7. All methods of interface need to be implemented by a class implementing that interface.
  8. Interfaces cannot contain body of any of its method.
51. What are queues and stacks?
Stacks refer to a list in which all items are accessed and processed on the Last-In-First-Out (LIFO) basis. In a stack, elements are inserted (push operation) and deleted (pop operation) from the same end called top.

Queues refer to a list in which insertion and deletion of an item is done on the First-In-First-Out (FIFO) basis. The items in a queue are inserted from the one end, called the rear end, and are deleted from the other end, called the front end of the queue.
52. Define an event.
Whenever an action takes place in a class, that class provides a notification to other classes or objects that are assigned to perform particular tasks. These notifications are called events. For example, when a button is clicked, the class generates an event called Click. An event can be declared with the help of the event keyword.
53. What are structures?
Structure is a heterogeneous collection of elements referenced by the same name. A structure is declared using the struct keyword. The following is an example that creates a structure to store an employee's information:
struct emp
{
 fixed int empID[15];
 fixed char name[30];
 fixed char addr[50];
 fixed char dept[15];
 fixed char desig[15];
}
The preceding example defines a structure emp and the members of this structure specify the information of an employee.
54. When do you really need to create an abstract class?
We define abstract classes when we define a template that needs to be followed by all the derived classes























Monday, November 4, 2013

c# basics


OOPS

What is Object Oriented Programming?
It is a problem solving technique to develop software systems. It is a technique to think real world
in terms of objects. Object maps the software model to real world concept. These objects have
responsibilities and provide services to application or other objects.
What’s a Class?
A class describes all the attributes of objects, as well as the methods that implement the behavior of
member objects. It’s a comprehensive data type which represents a blue print of objects. It’s a template
of object.
What’s an Object?
It is a basic unit of a system. An object is an entity that has attributes, behavior, and identity. Objects are
members of a class. Attributes and behavior of an object are defined by the class definition.
What is the relation between Classes and Objects?
They look very much same but are not same. Class is a definition, while object is a instance of the class
created. Class is a blue print while objects are actual objects existing in real world. Example we have
class CAR which has attributes and methods like Speed, Brakes, Type of Car etc. Class CAR is just a
prototype, now we can create real time objects which can be used to provide functionality. Example we
can create a Maruti car object with 100 km speed and urgent brakes.

What is Abstraction?
It allows complex real world to be represented in simplified manner. Example color is abstracted to
RGB. By just making the combination of these three colors we can achieve any color in world.It’s a
model of real world or concept.

What is Encapsulation?
It is a process of hiding all the internal details of an object from the outside world.
What is Object lifetime?
All objects have life time.Objects are created ,and initialized, necessary functionalities are done and
later the object is destroyed. Every object have there own state and identity which differ from instance to
instance.
What is Association?
This is the simplest relationship between objects. Example every customer has sales. So Customer object
and sales object have an association relation between them.
What is Aggregation?
This is also called as composition model. Example in order to make a "Accounts" class it has use other
objects example "Voucher", "Journal" and "Cash" objects. So accounts class is aggregation of these three
objects.
What is Polymorphism?
When inheritance is used to extend a generalized class to a more specialized class, it includes behavior of
the top class(Generalized class). The inheriting class often implement a behavior that can be somewhat
different than the generalized class, but the name of the behavior can be same. It is important that a given
instance of an object use the correct behavior, and the property of polymorphism allows this to happen
automatically.
What are abstract classes?
Following are features of a abstract class :-
1. You can not create a object of abstract class.
2. Abstract class is designed to act as a base class (to be inherited by other classes). Abstract class is a
design concept in program development and provides a base upon which other classes are built.
3. Abstract classes are similar to interfaces. After declaring an abstract class, it cannot be instantiated on
its own, it must be inherited.
4. In VB.NET abstract classes are created using "MustInherit" keyword.In C# we
have "Abstract" keyword.
5. Abstract classes can have implementation or pure abstract methods which should be implemented in
the child class.
What is a Interface?
Implementing a interface it says to the outer world, that it provides specific behavior. Example if a
class is implementing Idisposable interface that means it has a functionality to release unmanaged
resources. Now external objects using this class know that it has contract by which it can dispose unused
unmanaged objects. Single Class can implement multiple interfaces.
If a class implements a interface then it has to provide implementation to all its methods.
What is difference between abstract classes and interfaces?
Following are the differences between abstract and interfaces :-
1. Abstract classes can have concrete methods while interfaces have no methods implemented.
2. Interfaces do not come in inheriting chain, while abstract classes come in inheritance.
What is a delegate?
Delegate is a class that can hold a reference to a method or a function. Delegate class has a signature and
it can only reference those methods whose signature is compliant with the class. Delegates are type-safe
functions pointers or callbacks.

Do events have return type?
No, events do not have return type.
Can event’s have access modifiers?
Event’s are always public as they are meant to serve every one registering to it. But you can access
modifiers in events.You can have events with protected keyword which will be accessible only to

inherited classes.You can have private events only for object in that class.
Can we have shared events?
Yes, you can have shared event’s. Note: Only shared methods can raise shared events.
What is shadowing?
When two elements in a program have same name, one of them can hide and shadow the other one. So in
such cases the element which shadowed the main element is referenced.
What is the difference between Shadowing and Overriding?
Following are the differences between shadowing and overriding :-
1. Overriding redefines only the implementation while shadowing redefines the whole element.
2. In overriding derived classes can refer the parent class element by using "ME" keyword, but in
shadowing you can access it by "MYBASE"
What is the difference between delegate and events?
Actually events use delegates in bottom. But they add an extra layer on the delegates, thus forming the
publisher and subscriber model.
As delegates are function to pointers they can move across any clients. So any of the clients can add
or remove events, which can be pretty confusing. But events give the extra protection by adding the
layer and making it a publisher and subscriber model. 212 Just imagine one of your clients doing this
c.XyzCallback = null This will reset all your delegates to nothing and you have to keep searching where
the error is.
If we inherit a class do the private variables also get inherited?
Yes, the variables are inherited but can not be accessed directly by the class interface
What are the different accessibility levels defined in .NET?
Following are the five levels of access modifiers :-
1. Private : Only members of class have access.
2. Protected :-All members in current class and in derived classes can access the variables.
3. Friend (internal in C#) :- Only members in current project have access to the elements.
4. Protected friend (protected internal in C#) :- All members in current project and all members in
derived class can access the variables.
5. Public :- All members have access in all classes and projects.
Can you prevent a class from overriding?
If you define a class as "Sealed" in C# and "NotInheritable" in VB.NET you can not inherit the class
any further.
What is the use of "MustInherit" keyword in VB.NET?
If you want to create a abstract class in VB.NET it’s done by using "MustInherit" keyword.You can not
create an object of a class which is marked as "MustInherit". When you define "MustInherit" keyword
for class you can only use the class by inheriting.
Do interface have accessibility modifier?
All elements in Interface should be public. So by default all interface elements are public by default.
What are similarities between Class and structure?
Following are the similarities between classes and structures :-
1. Both can have constructors, methods, properties, fields, constants, enumerations, events, and event
handlers.
2. Structures and classes can implement interface.
3. Both of them can have constructors with and without parameter.
4. Both can have delegates and events.
What is the difference between Class and structure’s?
Following are the key differences between them :-
1.Structure are value types and classes are reference types. So structures use stack and classes use heap.
2. Structures members can not be declared as protected, but class members can be. You can not do
inheritance in structures.

3. Structures do not require constructors while classes require.
4.Objects created from classes are terminated using Garbage collector. Structures are not destroyed using
GC.
What does virtual keyword mean?
They are that method and property can be overridden.
What are shared (VB.NET)/Static(C#) variables?
Static/Shared classes are used when a class provides functionality which is not specific to any instance.
In short if you want an object to be shared between multiple instances you will use a static/Shared class.
Following are features of Static/Shared classes :-
1. They can not be instantiated. By default a object is created on the first method call to that object.
2. Static/Shared classes can not be inherited.
3. Static/Shared classes can have only static members.
4. Static/Shared classes can have only static constructor.
What is Dispose method in .NET?
NET provides "Finalize" method in which we can clean up our resources. But relying on this is not
always good so the best is to implement "Idisposable" interface and implement the "Dispose" method
where you can put your clean up routines.
What is the use of "OverRides" and "Overridable" keywords?
Overridable is used in parent class to indicate that a method can be overridden. Overrides is used in the
child class to indicate that you are overriding a method.
Where are all .NET Collection classes located?
System.Collection namespace has all the collection classes available in .NET.
What is ArrayList?
Array is whose size can increase and decrease dynamically. Array list can hold item of different types.
As Array list can increase and decrease size dynamically you do not have to use the REDIM keyword.
You can access any item in array using the INDEX value of the array position.
What’s a HashTable?
You can access array using INDEX value of array, but how many times you know the real value of
index. Hashtable provides way of accessing the index using a user identified KEY value, thus removing
the INDEX problem.
What are queues and stacks?
Queue is for first-in, first-out (FIFO) structures. Stack is for last-in, first-out (LIFO) structures.
What is ENUM?
It’s used to define constants.
What is Operator Overloading in .NET?
It allows us to define/redefine the way operators work with our classes and structs. This allows
programmers to make their custom types look and feel like simple types such as int and string. VB.NET
till now does not support operator overloading. Operator overloading is done by using the "Operator"
keyword. Note:- Operator overloading is supported in VB.NET 2005.
What is the significance of Finalize method in .NET?
.NET Garbage collector does almost all clean up activity for your objects. But unmanaged resources
(ex: - Windows API created objects, File, Database connection objects, COM objects etc) is outside the
scope of .NET framework we have to explicitly clean our resources. For these types of objects .NET
framework provides Object. Finalize method 218 which can be overridden and clean up code for
unmanaged resources can be put in this section.
Why is it preferred to not use finalize for clean up?
Problem with finalize is that garbage collection has to make two rounds in order to remove objects
which have finalize methods. Below figure will make things clear regarding the two rounds of garbage
collection rounds performed for the objects having finalized methods. In this scenario there are three
objects Object1, Object2 and Object3. Object2 has the finalize method overridden and remaining

objects do not have the finalize method overridden. Now when garbage collector runs for the first time
it searches for objects whose memory has to free. He can see three objects but only cleans the memory
for Object1 and Object3. Object2 it pushes to the finalization queue. Now garbage collector runs for
the second time. He see’s there are no objects to be released and then checks for the finalization queue
and at this moment it clears object2 from the memory. So if you notice that object2 was released from
memory in the second round and not first. That’s why the best practice is not to write clean up Non.NET
resources in Finalize method rather use the DISPOSE.
How can we suppress a finalize method?
GC.SuppressFinalize ()
What is the use of DISPOSE method?
Dispose method belongs to IDisposable interface. We had seen in the previous section how bad it can be
to override the finalize method for writing the cleaning of unmanaged resources. So if any object wants
to release its unmanaged code best is to implement 220 IDisposable and override the Dispose method of
IDisposable interface. Now once your class has exposed the Dispose method it’s the responsibility of the
client to call the Dispose method to do the cleanup.
How do I force the Dispose method to be called automatically, as clients can forget to call Dispose
method?
Call the Dispose method in Finalize method and in Dispose method suppress the finalize method
using GC.SuppressFinalize. Below is the sample code of the pattern. This is the best way we do clean
our unallocated resources and yes not to forget we do not get the hit of running the Garbage collector
twice. Note:- It will suppress the finalize method thus avoiding the two trip. Public Class ClsTesting
Implements IDisposable Public Overloads Sub Dispose()Implements IDisposable.Dispose ' write ytour
clean up code here GC.SuppressFinalize(Me) End Sub Protected Overrides Sub Finalize() Dispose() End
Sub End Class
In what instances you will declare a constructor to be private?
When we create a private constructor, we can not create object of the class directly from a client. So you
will use private constructors when you do not want instances of the class to be created by any external
client. Example UTILITY functions in project will have no 221 instance and be used with out creating
instance, as creating instances of the class would be waste of memory.
Can we have different access modifiers on get/set methods of a property?
No we can not have different modifiers same property. The access modifier on a property applies to both
its get and set accessors.
we write a goto or a return statement in try and catch block will the finally block execute?
The code in then finally always run even if there are statements like goto or a return statements.
What is Indexer?
An indexer is a member that enables an object to be indexed in the same way as an array.
Can we have static indexer in C#?
No
In a program there are multiple catch blocks so can it happen that two catch blocks are executed?
No, once the proper catch section is executed the control goes finally to block. So there will not be any
scenarios in which multiple catch blocks will be executed.

What is the difference between System.String and System.StringBuilder classes?
System.String is immutable; System.StringBuilder can have mutable string where a variety of operations
can be performed.


Access Specifiers 




In C#, the new keyword can be used as an operator, a modifier, or a constraint.
new Operator
Used to create objects and invoke constructors.
new Modifier
Used to hide an inherited member from a base class member.
new Constraint
Used to restrict types that might be used as arguments for a type parameter in a generic declaration.



The sealed modifier can be applied to classes, instance methods and properties. A sealed class cannot be inherited. A sealed method overrides a method in a base class, but itself cannot be overridden further in any derived class. When applied to a method or property, the sealed modifier must always be used with override (C# Reference).
Use the sealed modifier in a class declaration to prevent inheritance of the class, as in this example:
      sealed class SealedClass 
{
    public int x; 
    public int y;
}

// cs_sealed_keyword.cs
using System;
sealed class SealedClass
{
    public int x;
    public int y;
}

class MainClass
{
    static void Main()
    {
        SealedClass sc = new SealedClass();
        sc.x = 110;
        sc.y = 150;
        Console.WriteLine("x = {0}, y = {1}", sc.x, sc.y);
    }
}


The abstract modifier can be used with classes, methods, properties, indexers, and events. Use the abstract modifier in a class declaration to indicate that a class is intended only to be a base class of other classes. Members marked as abstract, or included in an abstract class, must be implemented by classes that derive from the abstract class.
In this example, the class Square must provide an implementation of Area because it derives from ShapesClass:
      abstract class ShapesClass
{
    abstract public int Area();
}
class Square : ShapesClass
{
    int x, y;
    // Not providing an Area method results
    // in a compile-time error.
    public override int Area()
    {
        return x * y;
    }
}


Abstract classes have the following features:
  • An abstract class cannot be instantiated.
  • An abstract class may contain abstract methods and accessors.
  • It is not possible to modify an abstract class with the sealed (C# Reference) modifier, which means that the class cannot be inherited.
  • A non-abstract class derived from an abstract class must include actual implementations of all inherited abstract methods and accessors.
Use the abstract modifier in a method or property declaration to indicate that the method or property does not contain implementation.
Abstract methods have the following features:
  • An abstract method is implicitly a virtual method.
  • Abstract method declarations are only permitted in abstract classes.
  • Because an abstract method declaration provides no actual implementation, there is no method body; the method declaration simply ends with a semicolon and there are no curly braces ({ }) following the signature. For example:
    public abstract void MyMethod();
    
  • The implementation is provided by an overriding methodoverride (C# Reference), which is a member of a non-abstract class.
  • It is an error to use the static or virtual modifiers in an abstract method declaration.
Abstract properties behave like abstract methods, except for the differences in declaration and invocation syntax.
  • It is an error to use the abstract modifier on a static property.
  • An abstract inherited property can be overridden in a derived class by including a property declaration that uses the override modifier.
An abstract class must provide implementation for all interface members.


The internal keyword is an access modifier for types and type members. Internal types or members are accessible only within files in the same assembly, as in this example:

The public keyword is an access modifier for types and type members. Public access is the most permissive access level. There are no restrictions on accessing public members, as in this 
The protected keyword is a member access modifier. A protected member is accessible within its class and by derived classes. For a comparison of protected with the other access modifiers, see Accessibility Levels.
protected
A protected member is accessible within its class and by derived classes.
internal
Internal types or members are accessible only within files in the same assembly.
protected internal
Access is limited to the current assembly or types derived from the containing class.
* protected internal is the only access modifiers combination allowed for a member or a type.
So, as we can see “protected internal” can be used in the same assembly or types derived from the containing class in any assembly.
It means that we can access a “protected internal” method by accessing any instance of it’s class in the same assembly, in any class in different assembly which derives from the class, but we won’t be able to access the method by accessing an instance of it’s class in different assembly.
  1. // Assemby : A  
  2. namespace AssemblyA  
  3. {  
  4.     public class A  
  5.     {  
  6.         protected internal string SomeProtectedInternalMethod() {  
  7.             return "SomeValue";  
  8.         }  
  9.     }  
  10.   
  11.     public class A2 : A  
  12.     {  
  13.         public string SomeMethod() {  
  14.             // We can access the method because  
  15.             // it's protected and inherited by A2  
  16.             return SomeProtectedInternalMethod();  
  17.         }  
  18.     }  
  19.   
  20.     class A3 : A  
  21.     {  
  22.         public string SomeMethod()  
  23.         {  
  24.             A AI = new A();  
  25.             // We can access the method through an instance  
  26.             // of the class because it's internal  
  27.             return AI.SomeProtectedInternalMethod();  
  28.         }  
  29.     }  
  30. }  
  1. // Assemby : B  
  2. using AssemblyA;  
  3. namespace AssemblyB  
  4. {  
  5.     class B : A  
  6.     {  
  7.         public string SomeMethod() {  
  8.             // We can access the method because  
  9.             // it's inherited by A2  
  10.             // despite the different assembly  
  11.             return SomeProtectedInternalMethod();  
  12.         }  
  13.     }  
  14.   
  15.     class B2  
  16.     {  
  17.         public string SomeMethod()  
  18.         {  
  19.             A AI = new A();  
  20.             // We can't access the method  
  21.             // through the class instance  
  22.             // because it's different assembly  
  23.             return AI.SomeProtectedInternalMethod();  
  24.         }  
  25.     }  
  26. } 

MONDAY, NOVEMBER 19, 2012

OOPS

OOPS:


Abstract class:

    A class that serves only as a base class from which classes are derived. No objects of an abstract base class are created.
Ex:vb.net
Public mustinherit class person
{
//implementation
}
C#.net
Abstract class person
{
//implementation
}

For these classes we can’t create an object directly. We are declare one derived class and to inherit the base class. Then only we create an object to derived class.

Inheritance:

A relationship between classes such that some of the members declared in one class (base class) are also representing in the second class (derived class). The derived class inherits the members from the base class.

Multiple inheritance:

Multiple inheritance is a derived class declared to inherit properties of two or more parent classes.

Ex: vb.net:

Public class c1
 Public function hai() as string
    Msgbox(hi)
End class
Public class C2 inherits C1
    Msgbox(bye)
End class
Main()
Dim obj as new C2
C2.hai()
o/p: hi

C#.net:

Class C1
{
    Public string hai();
    MessageBox show(“hi”);
}
Class C2:C1
{
    Void Bye()
{
        MessageBox.show(“bye”);
}
}
Main()
{
    C2 obj=new C2;
    Obj.hai();
    Obj.Bye();
}

o/p: hi, Bye

Interface:

An interface can be defined as selection of subprogram without functionality.

Syntax: by default it is public
Vb.net:

Public interface <name>
    Sub setname(ename as string)
    Function Getname() as string
End interface
Public class emp implements person
    Dim name as string
Sub Setname(ename as string) implements person.setname
    Name=personname
End sub
Function getname() as string
End function return getname

C#.net:

Public interface <name>
{
    Void hello()
}
Class emp:person
{
    Void hello()
    {
        Messagebox.show(“hello”);
    }
}
End class

Note: you can’t create an instance of interface

Overridable:

    To indicate that a method may be overridden.





Ex: vb.net

Class C1
Public overridable subXX(0
Msgbox(“welcome”)
End class

Class C2
Public overrides subXX()
    Msgbox(“Bye”)
End class

Obj.XX()-> Bye->o/p

C#.net

Class C1{
    Public virtual string XX()
    {
        Msgbox.show(“welcome”);
    }
}
Class C2:C1
{
    Public override string XX()
    {
        Msgbox.show(“Bye”);
    }
}
Obj C2=new C2;
Obj.XX -> o/p=Bye


Must override:

To indicate that derived classes must provide their own implementation of a method using must override creates pure virtual also called abstract methods. These methods may not be used directly, but must be overriden.

Ex: vb.net

Public mustoverride subXX()
    Msgbox(“bye”)
End sub

C#.net:

Public abstract string XX()
        Msgbox.show(“bye”)

Not overriden:
To indicate that a method may not be overriden.

Vb.net:
Public Notoverridable subxx()
    Msgbox(“hai”)
End sub
Must inherits:

The class which doesn’t support instance creation is called must inherit class. In C++, Java it is called abstract class.
Ex: vb.net

Must inherits class C1
Public mustoverridable subxx()

End class

Class C2 inherits C1
Public overrides subxx()


  • Class: Logical representation of data.
  • Object: Physical representation of data.
  • Constructor: A special member function for automatically creating an instance of a class.
  • Destructor: A function that is called to deallocate memory of the object of a class.

Not inheritable:
The class which doesn’t support inheritance is called sealed class.
Ex: vb.net
Not inherits class C1
C#.net
Sealed class C1
Mybase:
To access methods in a base class when overriding methods in a derived class.

Me:
Me keywords provides us with a reference to our current object instance.
Myclass:
To call an overridable method in your class while making sure that implementation of the method in your class is called instead of an overridden version of the method.

Shadows:
The shadows keyword allows us to replace methods on the base class that the base class designer didn’t intend to be replaced.

Ex:
Vb.net:
Public shadows Readonly property  xx()Intiger
   Get
        Return 3.8
    End get
 End property
End class

Shared:

Shared data -> Shared Method -> Shared Constructor

Shared data:  when the data is attached to the class then it is called as shared data. This data will have only one memory instance which will be common to all the objects of the class.

Ex: public shared eno as byte

Shared method:   the method which is attached to the class is called as shared method. This method can access only by shared data.
Ex: public shared function XX() as byte

C#.net-> public static int xx()

Early binding:  Early binding means that our code directly interacts with the object by directly calling its method.(compilation time)

Late binding:   Late binding means that our code interacts with an object dynamically at runtime.

Access Modifiers:  

  1. Public : Entities declared Public have public access.There is no restrictions on the accessibility of the public entities.
  2. Private : Entities declared private have private access. They are accessible from their declaration context.

  1. Protected : Entities declared Protected have protected access. They are accessible only from within their own class or from a derived class. It is not a superset of friend class. You can use protected only at class level.

  1. Protected Friend: (protected internal) Entities declared in the protected friend have both protected and friend access. They can be used by code in the same class or as well as in derived class. The rules for protected and friend apply to protected friend as well.

  1. Friend: A function that has access to the private members of a class but is not itself a member of the class. An entire class can be a friend of another class.

Encapsulation: The mechanism by which the data and funtions ( manipulatiing this data) are bound together within an object definition.

Boxing: when we are converting value type as a reference type on the heap memory then it is called Boxing.

Ex: int a=20; Object b=a;It work implicitly.

Unboxing: when we are converting reference type to value type then it is called Unboxing. This will maintain on overhead towards the application. This will decrease the performance of application.

Ex: object a=20: int b=a;  Int b=int(a) -> implicit

Meta data: the collected information that describes an application is called metadata.

Name space: Name space is nothing but logical container for collection of classes.

  • Name space helps organize object libraries and hierarchies.
  • Simplify object references, prevent ambiguity when reffering to objects, and control the scope of object identifiers.

System collections: The collections name space is a part of the system name space and provides a series of classed that implement advanced array features.

  1. Array list: implements an array whose size increases automatically as elements are added.
  2. Bit array: Manages an array of Boolean that are stored as bits.
  3. Hash table:  Implements a collection of values organized by key. Sorting is done.

  1. Queue: Implements first in first out (fifo)

  1. Sorted list: Implements a collection of values with associated keys. The values are stored by key, and accessible by key or index.
  2. Stack: implements Last in First out(lifO)

System diagnostics: this name space provides classes that allow you to interact with system process, event logs and performance counters.

Deploymet: It is the process of taking an application and installing it on another machine.

Cabproject -> mergemodule project(.msm) -> setup project -> websetup project

Delegate:  a delegate is a class which acts as a function pointer.

    Features:

  1. It is provided with object-Oriented approach
  2. It refers to method of the object.
  3. A delegate is useful when you want to send one subprogram as a parameter to another subprogram.

Syntax: public Deligate sub XX()


Multicast deligate: it is a delegate that points to and eventually fires off several methods.

Thread: A thread can be defined as a unit of code having it’s own executing part.

  • Single thread: when the application is having only one process then it is called as single thread application.

  • Multi thread: when the application is having more than one process then it is called as multi thread application.
Methods: start(), shared sleep, suspend, resume, abort, join.

Asyschronus connection: ADO.net provides an option for asynchronous connection this can be achieved by multi threading.

Synchronization of threads:  Synchronization of the thread is allowing only one thread to work with block of statements. This can be achieved by applying the lock for set of statements.
Keyword:  synclock(“L1”)

Thread prorites: Above normal, normal, below normal, minimum.