Tuesday 9 November 2010

Object Oriented Programming with C#

What is the difference between struct and class in C#?
Structs vs classes in C#
Structs may seem similar to classes, but there are important differences that you should be aware of. First of all, classes are reference types and structs are value types. By using structs, you can create objects that behave like the built-in types and enjoy their benefits as well.

* When you call the New operator on a class, it will be allocated on the heap. However, when you instantiate a struct, it gets created on the stack. This will yield performance gains. Also, you will not be dealing with references to an instance of a struct as you would with classes. You will be working directly with the struct instance. Because of this, when passing a struct to a method, it’s passed by value instead of as a reference.
* Structs can declare constructors, but they must take parameters. It is an error to declare a default (parameterless) constructor for a struct. Struct members cannot have initializers. A default constructor is always provided to initialize the struct members to their default values.

How do I call one constructor from another in C#?
You use : base (parameters) or : this (parameters) just before the actual code for the constructor, depending on whether you want to call a constructor in the base class or in this class.

What is the difference between indexers and properties in C#?
Comparison Between Properties and Indexers
Indexers are similar to properties. Except for the differences shown in the following , all of the rules defined for property accessors apply to indexer accessors as well.

Properties
Identified by its name.
Accessed through a simple name or a member access.
Can be a static or an instance member.
A get accessor of a property has no parameters.
A set accessor of a property contains the implicit value parameter.

Indexers
Identified by its signature.
Accessed through an element access.
Must be an instance member.
A get accessor of an indexer has the same formal parameter list as the indexer.
A set accessor of an indexer has the same formal parameter list as the indexer, in addition to the value parameter.

Which interface(s) must a class implement in order to support the foreach statement?
Required interface for foreach statement:
A class must implement the IEnumerable and IEnumerator interfaces to support the foreach statement.

Explain Abstract, Sealed, and Static Modifiers in C#.
C# provides many modifiers for use with types and type members. Of these, three can be used with classes: abstract, sealed and static.

abstract
Indicates that a class is to be used only as a base class for other classes. This means that you cannot create an instance of the class directly. Any class derived from it must implement all of its abstract methods and accessors. Despite its name, an abstract class can possess non-abstract methods and properties.

sealed
Specifies that a class cannot be inherited (used as a base class). Note that .NET does not permit a class to be both abstract and sealed.

static
Specifies that a class contains only static members (.NET 2.0).

What’s the difference between override and new in C#?
This is all to do with polymorphism. When a virtual method is called on a reference, the actual type of the object that the reference refers to is used to decide which method implementation to use. When a method of a base class is overridden in a derived class, the version in the derived class is used, even if the calling code didn’t “know” that the object was an instance of the derived class. For instance:

public class Base
{
public virtual void SomeMethod()
{
}
}

public class Derived : Base
{
public override void SomeMethod()
{
}
}



Base b = new Derived();
b.SomeMethod();

will end up calling Derived.SomeMethod if that overrides Base.SomeMethod.

Name two ways that you can prevent a class from being instantiated.
Ways to prevent a class from instantiated:

A class cannot be instantiated if it is abstract or if it has a private constructor.

Explain some features of interface in C#.
Comparison of interface with class (interface vs class):

* An interface cannot inherit from a class.
* An interface can inherit from multiple interfaces.
* A class can inherit from multiple interfaces, but only one class.
* Interface members must be methods, properties, events, or indexers.
* All interface members must have public access (the default).
* By convention, an interface name should begin with an uppercase I.

Can an abstract class have non-abstract methods?
An abstract class may contain both abstract and non-abstract methods. But an interface can contain only abstract methods.

How do I use an alias for a namespace or class in C#?
Use the using directive to create an alias for a long namespace or class. You can then use it anywhere you normally would have used that class or namespace. The using alias has a scope within the namespace you declare it in.

Sample code:

// Namespace:
using act = System.Runtime.Remoting.Activation;

// Class:
using list = System.Collections.ArrayList;

list l = new list(); // Creates an ArrayList
act.UrlAttribute obj; // Equivalent to System.Runtime.Remoting.Activation.UrlAttribute obj

What type of class cannot be inherited?
A sealed class cannot be inherited. A sealed class is used primarily when the class contains static members. Note that a struct is implicitly sealed; so they cannot be inherited.

What keyword must a derived class use to replace a non-virtual inherited method?
new keyword is used to replace (not override) an inherited method with one of the same name.

What is polymorphism in Object Oriented Programming (OOPS) Languages?
In object-oriented programming, polymorphism is a generic term that means ‘many shapes’. (from the Greek meaning “having multiple forms”). Polymorphism is briefly described as “one interface, many implementations.” polymorphism is a characteristic of being able to assign a different meaning or usage to something in different contexts – specifically, to allow an entity such as a variable, a function, or an object to have more than one form.

There are two types of polymorphism one is compile time polymorphism and the other is run time polymorphism. Compile time polymorphism is functions and operators overloading. Runtime time polymorphism is done using inheritance and virtual functions. Here are some ways how we implement polymorphism in Object Oriented programming languages

Interface and abstract methods
Like in C# or JAVA different classes implement a common interface in different ways; is an example of Runtime polymorphism. The interface defines the abstract member functions (no implementation). In class that implement the interface; we define body of those abstract members according to the requirement. Means single definition in interface but multiple implementation in child classes.

Virtual member functions
Using virtual member functions in an inheritance hierarchy allows run-time selection of the appropriate member function. A virtual function is a member function of the base class and which is redefined by the derived class. Such functions can have different implementations that are invoked by a run-time determination of the subtype (virtual method invocation, dynamic binding).

Function Overloading
Polymorphism means that functions assume different forms at different times. In case of compile time it is called function overloading.Two or more functions can have same name but their parameter list should be different either in terms of parameters or their data types. The functions which differ only in their return types cannot be overloaded. The compiler will select the right function depending on the type of parameters passed.

Operator Overloading
In polymorphism operators can also be overloaded (Compile time polymorphism). Operators can be overloaded in order to perform special functions with respect to the class. With the help of operator overloading standard operations such as + , – , * , etc can be applied on the objects of the class.

What is a Virtual Functions in class?
A virtual function is a member function of the base class and which is redefined by the derived class. When a derived class inherits the class containing the virtual function, it has ability to redefine the virtual functions.

A virtual function has a different functionality in the derived class according to the requirement. The virtual function within the base class provides the form of the interface to the function. Virtual function implements the philosophy of one interface and multiple methods (polymorphism).

The virtual functions are resolved at the run time. This is called dynamic binding. The functions which are not virtual are resolved at compile time which is called static binding. A virtual function is created using the keyword virtual which precedes the name of the function.

What is Encapsulation in Object Oriented Programming (OOPS) Languages?
Encapsulation is the procedure of covering up of data and functions into a single unit. Encapsulation (also information hiding) consists of separating the external aspects of an object which are accessible to other objects, from the internal implementation details of the object, which are hidden from other objects.

A process, encapsulation means the act of enclosing one or more items within a (physical or logical) container (Class).

Object-oriented programming is based on encapsulation. When an objects state and behavior are kept together, they are encapsulated. That is, the data that represents the state of the object and the methods (Functions and Subs) that manipulate that data are stored together as a cohesive unit.

The object takes requests from other client objects, but does not expose its the details of its data or code to them. The object alone is responsible for its own state, exposing public messages for clients, and declaring private methods that make up its implementation. The client depends on the (hopefully) simple public interface, and does not know about or depend on the details of the implementation.

For example, a HashTable object will take get() and set() requests from other objects, but does not expose its internal hash table data structures or the code strategies that it uses.

Explain the advantages of Encapsulation in Object Oriented Programming Languages.
Benefits of Encapsulation in oops:
Encapsulation makes it possible to separate an objects implementation from its behavior to restrict access to its internal data. This restriction allows certain details of an objects behavior to be hidden. It allows us to create a “black box” and protects an objects internal state from corruption by its clients.

Encapsulation is a technique for minimizing interdependencies among modules by defining a strict external interface. This way, internal coding can be changed without affecting the interface, so long as the new implementation supports the same (or upwards compatible) external interface. So encapsulation prevents a program from becoming so interdependent that a small change has massive ripple effects.

The implementation of an object can be changed without affecting the application that uses it for: Improving performance, fix a bug, consolidate code or for porting.

Limitations and Restrictions of Interface
The essential idea to remember is that an interface never contains any implementation. The following restrictions and imitations are natural consequences of this:

You’re not allowed any fields in an interface, not even static ones. A field is an implementation of an object attribute.

You’re not allowed any constructors in an interface. A constructor contains the statements used to initialize the fields in an object, and an interface does not contain any fields!

You’re not allowed a destructor in an interface. A destructor contains the statements used to destroy an object instance.

You cannot supply an access modifier. All methods in an interface are implicitly public.

You cannot nest any types (enums, structs, classes, interfaces, or delegates) inside an interface.

What is an Object?
An object is an instance of a class. It can be uniquely identified by its name and it defines a state which is represented by the values of its attributes at a particular time.

An object can be considered a “thing” that can perform a set of activities. The set of activities that the object performs defines the object’s behavior.

The state of the object changes according to the methods which are applied to it. We refer to these possible sequences of state changes as the behavior of the object. So the behavior of an object is defined by the set of methods which can be applied on it.

Objects can communicate by passing messages to each other.

What is inheritance?
Inheritance is the mechanism which allows a class A to inherit properties of a class B. We say “A inherits from B”. Objects of class A thus have access to attributes and methods of class B without the need to redefine them.

If class A inherits from class B, then B is called superclass of A. A is called subclass of B. Objects of a subclass can be used where objects of the corresponding superclass are expected. This is due to the fact that objects of the subclass share the same behavior as objects of the superclass.

However, subclasses are not limited to the state and behaviors provided to them by their superclass. Subclasses can add variables and methods to the ones they inherit from the superclass.

In the literature you may also find other terms for “superclass” and “subclass”. Superclasses are also called parent classes or base classes. Subclasses may also be called child classes or just derived classes.

Inheritance Example
Like a car, truck or motorcycles have certain common characteristics- they all have wheels, engines and brakes. Hence they all could be represented by a common class Vehicle which encompasses all those attributes and methods that are common to all types of vehicles.

However they each have their own unique attributes; car has 4 wheels and is smaller is size to a truck; whereas a motorcycle has 2 wheels. Thus we see a parent-child type of relationship here where the Car, Truck or Motorcycle can inherit certain Characteristics from the parent Vehicle; at the same time having their own unique attributes. This forms the basis of inheritance; Vehicle is the Parent, Super or the Base class. Car, Truck and Motorcycle become the Child, Sub or the Derived class.

Explain some characteristics of inheritance.
A class inherits the members of its direct base class. Inheritance means that a class implicitly contains all members of its direct base class, except for the constructors and destructors of the base class.

Some important aspects of inheritance are:

Inheritance is transitive. If C is derived from B, and B is derived from A, then C inherits the members declared in B as well as the members declared in A.

A derived class extends its direct base class. A derived class can add new members to those it inherits, but it cannot remove the definition of an inherited member.

Constructors and destructors are not inherited, but all other members are, regardless of their declared accessibility. However, depending on their declared accessibility, inherited members might not be accessible in a derived class.

A derived class can hide inherited members by declaring new members with the same name or signature. Note however that hiding an inherited member does not remove that member; it merely makes that member inaccessible in the derived class.

An instance of a class contains a set of all instance fields declared in the class and its base classes, and an implicit conversion exists from a derived class type to any of its base class types. Thus, a reference to an instance of some derived class can be treated as a reference to an instance of any of its base classes.

A class can declare virtual methods, properties, and indexers, and derived classes can override the implementation of these function members. This enables classes to exhibit polymorphic behavior wherein the actions performed by a function member invocation varies depending on the run-time type of the instance through which that function member is invoked.

No comments:

Post a Comment