Friday 27 January 2012

What is Serialization? What is serializable attribute used for?

Serialization - The process of converting an object into a stream of bytes. This stream of bytes can be persisted. Deserialization is an opposite process, which involves converting a stream of bytes into an object. Serialization is used usually during remoting (while transporting objects) and to persist file objecst & database objects.

.NET provides 2 ways for serializtion 1) XmlSerializer and 2) BinaryFormatter/SoapFormatter


The XmlSerializer is used for Web Services. The BinaryFormatter & SoapFormatter is used for Remoting. While using XmlSerializer, it is required that the target class has parameter less constructors, has public read-write properties and has fields that can be serialized. The XmlSerializer has good support for XML documents. It can be used to construct objects from existing XML documents. The XmlSerializer enables us to serialize and deserialize objects to an XML format.

SoapFormatter
enables us to serialize & deserialize objects to SOAP format. They can serialize private and public fields of a class. The target class must be marked with the Serializable attribute. On deserialization, the constructor of the new object is not invoked.

The BinaryFormatter has the same features as the SoapFormatter except that it formats data into binary format. The BinaryForamatter (and the SoapFormatter) has two main methods. Serialize and Deserialize. To serialize an object, we pass an instance of the stream and the object to the Serialize method. To Deserialize an object, you pass an instance of a stream to the Deserialize method.

You can use the BinaryFormatter to serialize many, but not all, classes in the .NET Framework. For example, you can serialize ArrayLists, DataSets, and Arrays but not other objects, such as DataReaders or TextBox controls. To serialize a class, the class must have the Serializable attribute or implement the ISerializable interface.

Note that the XmlSerializer captures only the public members of the class, whereas the BinaryFormatter & the SoapFormatter captures both the public & private members of the class. The output using the BinaryFormatter is quite compact, as the information is in binary format, whereas the XmlSerializer format is filled with XML tags. See example below...
Imports System.IO
Imports System.Runtime.Serialization.Formatters.Binary
Dim colArrayList As ArrayListDim
objFileStream As FileStreamDim
objBinaryFormatter As BinaryFormattercolArrayList = New ArrayList()
colArrayList.Add( "Whisky")
colArrayList.Add( "Vodka")
colArrayList.Add( "Brandy")
objFileStream = New FileStream(MapPath("C:\myArrayList.data"), FileMode.Create)
objBinaryFormatter = New BinaryFormatterobjBinaryFormatter.Serialize(objFileStream, colArrayList)objFileStream.Close()
Here we see that an instance of the file stream (objFileStream) and an instance of the object (colArrayList) is passed to the Serialize method of the BinaryFormatter object (objBinaryFormatter). We also end up creating a file by the name myArrayList.data on our hard-drive.In order to deserialize an object, see the code below…
Dim colArrayList As ArrayListDim objFileStream As FileStreamDim
objBinaryFormatter As BinaryFormatterDim strItem As String
objFileStream = New FileStream( MapPath("myArrayList.data"), FileMode.Open )
objBinaryFormatter = New BinaryFormatter
colArrayList = CType( objBinaryFormatter.Deserialize( objFileStream ), ArrayList )
objFileStream.Close()
For Each strItem In colArrayList
Response.Write( "  " & strItem )
Next
Here, CType takes in two parameters, the first parameter is the serialized object in the file stream format, and the second parameter is the desired type. Finally, the page iterates through all the elements of the ArrayList and displays the value of each element.

XmlSerializer
does not serialize instances of classes like Hashtable which implement the IDictionary interface.

Serializable
- This is a class attribute. When we use this attribute with a class, an instance of this class can be taken in whatever state it is, and write it to a disk. The class can then be deserialized, and the class will act as if it is simply stored in the memory.

What is a static constructor?

Static Constructor - It is a special type of constructor, introduced with C#. It gets called before the creation of the first object of a class(probably at the time of loading an assembly). See example below.
Example:
public class SomeClass()
{
  static SomeClass()
  {
     //Static members may be accessed from here
     //Code for Initialization
   }
}
While creating a static constructor, a few things need to be kept in mind:
* There is no access modifier require to define a static constructor
* There may be only one static constructor in a class
* The static constructor may not have any parameters
* This constructor may only access the static members of the class
* We may create more than one static constructor for a class

Can a class be created without a constructor?

No. In case we dont define the constructor, the class will access the no-argument constructor from its base class. The compiler will make this happen during compilation.

What is Overloading? What is Overloads? What is Overload?

Overloading - is the concept of using one function or class in different ways by changing the signature of its parameters. We can define a function with multiple signatures without using the keyword Overloads, but if you use the Overloads keyword in one, you must use it in all of the function's Overloaded signatures.

The Overloads keyword is used in VB.NET, while the Overload keyword is used in C# (There is no other difference). The Overloads property allows a function to be described using deferent combinations of parameters. Each combination is considered a signature, thereby uniquely defining an instance of the method being defined.

Overloading is a way through which polymorphism is achieved.

What is an access modifier? What are the different types of Access modifiers?

Access Modifiers - Keywords used to change the way members of a class are accessed. The main purpose of using access specifiers is to provide security to the applications. The availability (scope) of the member objects of a class may be controlled using access specifiers.

What is a property? What is an event?

Property - A property is a thing that describes the features of an object. A property is a piece of data contained within a class that has an exposed interface for reading/writing. Looking at this definition, we might think we could declare a public variable in a class and call it a property. While this assumption is somewhat valid, the real technical term for a public variable in a class is a field. The main difference between a field and a property is in the inclusion of an interface.

We make use of Get and Set keywords while working with properties. We prefix the variables used within this code block with an underscore. Value is a keyword, that holds the value which is being retrieved or set.ss="a">
Private _Color As String
   Public Property Color()
    Get
      Return _Color
    End Get
    Set(ByVal Value)
      _Color = Value
    End Set
End Property
Event - An action that an object does. When something happens, we say an event has happened. For example, when a button is clicked, we say it is the click( ) event. When a mouse hovers on an image, we say the mouseover( ) event has taken place.

What is polymorphism?

Polymorphism means allowing a single definition to be used with different types of data (specifically, different classes of objects). For example, a polymorphic function definition can replace several type-specific ones, and a single polymorphic operator can act in expressions of various types. Many programming languages implement some forms of polymorphism.

The concept of polymorphism applies to data types in addition to functions. A function that can evaluate to and be applied to values of different types is known as a polymorphic function. A data type that contains elements of different types is known as a polymorphic data type.

Polymorphism may be achieved by overloading a function, overloading an operator, changing the order of types, changing the types using the same name for the member in context.
Example:
Public Class Calc
{
public void fnMultiply(int x, int y)
{ return x * y; }
public void fnMultiply(int x, int y, int z)
{ return x * y * z; }
}
...
...
Calc obj;

int Result;
Result = obj.fnMultiply(2,3,4); // The second fnMultiply would be called
Result = obj.fnMultiply(3,4); // The first fnMultiply would be called

Inheritance (object-oriented programming)

In object-oriented programming (OOP), inheritance is a way to reuse code of existing objects, establish a subtype from an existing object, or both, depending upon programming language support. In classical inheritance where objects are defined by classes, classes can inherit attributes and behavior (i.e., previously coded algorithms associated with a class) from pre-existing classes called base classes or superclasses or parent classes or ancestor classes. The new classes are known as derived classes or subclasses or child classes. The relationships of classes through inheritance gives rise to a hierarchy. In prototype-based programming, objects can be defined directly from other objects without the need to define any classes, in which case this feature is called differential inheritance.
Complex inheritance, or inheritance used within an insufficiently mature design, may lead to the yo-yo problem.
The inheritance concept was invented in 1968 for Simula.[1]

Subclasses and superclasses

A superclass, base class, or parent class is a class from which other classes have been derived. The classes that are derived from a superclass are known as subclasses, or derived classes, or child classes.
A superclass allows for a generic interface to include specialized functionality through the use of virtual functions.
The superclass mechanism is extensively used in object-oriented programming because of the reusability that can be achieved: common features are encapsulated in modular objects. Subclasses that wish to implement special behavior can do so via virtual methods, without having to reimplement the superclass's behavior.
A subclass is a class that inherits some properties from its superclass.
Subclasses and superclasses are often referred to as derived and base classes, respectively,

Applications

Inheritance is used to co-relate two or more classes to each other. With the use of inheritance we can use the methods and the instance variables of other classes in any other classes.

What is inheritance?

Inheritance - is the concept of passing the traits of a class to another class.

A class comprises of a collection of types of encapsulated instance variables and types of methods, events, properties, possibly with implementation of those types together with a constructor function that can be used to create objects of the class. A class is a cohesive package that comprises of a particular kind of compile-time metadata. A Class describes the rules by which objects behave; these objects are referred to as "instances" of that class. (Reference)

Classes can inherit from another class. This is accomplished by putting a colon after the class name when declaring the class, and naming the class to inherit from—the base class—after the colon. (Reference) 


 Whats the difference between a class and an object?


In any object Oriented language, an object is the backbone of everything that we see. A class is a blueprint that describes how an instance of it (object) will behave. To create a class, we define it in a "Code File", with an extension *.cs or *.vb. We make use of the keyword class.
Example
Lets create a class named Laptop
public class Laptop
{
  private string sbrand;
  public Laptop() {}
  public Laptop(string name)
  {
    sbrand = name;
  }
}

From our code that references this class, we write...

Laptop lp = new Laptop("Lenovo"); //Passing a variable to the class constructor
Once the class object is created, the object may be used to invoke the member functions defined within the class. We may allocate any number of objects using the new keyword. The new keyword returns a reference to an object on the heap. This reference is not to the actual object itself. The variable being refered is stored on a stack for usage in the application. When we allocate an object to a heap, its managed by the .NET runtime. The garbage collector takes care of the object by removing it from the heap, when it is no longer reachable by any part of the code.

What is a class member? What is an object?

The entities like events, properties, fields and functions encapsulated within a class are called class members. A constructor of a class that resides within it is also a form of a class member.

When we instantiate a class in order to use its encapsulated class members, this instantiated class entity is called the object. Difference between class & object

Friday 6 January 2012

What is Encapsulation?

Encapsulation - is the ability of an object to hide its data and methods from the rest of the world. It is one of the fundamental principles of OOPs.

Say we create a class, named Calculations. This class may contain a few members in the form of properties, events, fields or methods. Once the class is created, we may instantiate the class by creating an object out of it. The object acts as an instance of this class, the members of the class are not exposed to the outer world directly, rather, they are encapsulated by the class.
Example:
Public class Calculations
{
  private void fnMultiply(int x, int y)
  {
  return x * y;
  }
}
...
...
Calculations obj;

int Result;
Result = obj.fnMultiply(5,10);

What is a class? What is a Base Class?

A class is an organized store-house in object-oriented programming that gives coherent functional abilities to a group of related code. It is the definition of an object, made up of software code. Using classes, we may wrap data and behaviour together (Encapsulation). We may define classes in terms of classes (Inheritance). We can also override the behaviour of a class using an alternate behaviour (Polymorphism).

It is important to note that a class is a Reference Type. To know about Reference Types, Click Here

A Base Class is a class that is inherited by another class. In .NET, a class may inherit from only one class.
To know about Abstract Class, Click Here

What is OOPs?

OOPs - Object Oriented Programming Languages & Systems
Everything in the world is an object. The type of the object may vary. In OOPS, we get the power to create objects of our own, as & when required. OOPs is a programming methodology where each entity is an object.
It is a method of computer programming where entities of related data together with routines associated with it are treated as one object in the program.