Untitled Page

Monday, June 13, 2011

Serialization and De-serialization in C#

Serialization and De-serialization
Serialization is the process of writing objects to the stream while De-serialization is the process of reading objects
from the stream. Up until now, we have seen how to read/write primitive types to the streams but we haven’t
read/written any explicit (user defined) type to the stream. There are certain points that must be clear before
actually implementing the serialization.
The purpose of serializing or writing an object to a stream is to save its state. The state of an object is determined
by its instance variables. Hence serializing an object means writing all of its member (or instance) variables (also
called an object graph) to the stream. Methods or static members are not serialized or written to the stream.
You can serialize an object yourself by simply writing all of its member variables to the stream. When
de-serializing, you would have to read all the member variables in the same sequence in which they were written.
However this process of serializing and de-serializing has two major disadvantages:
• It is a tedious job to write all the member variables yourself and it might become hectic if your class
contains a lot of variables and if your class contains other user defined objects.
• It is not the standard procedure. The person who is willing to de-serialize the object you serialized
previously, would have to be aware of the sequence in which you wrote the member variables and must
follow that sequence.
The Dot (.Net) framework takes care of these issues and provides binary and SOAP formatters using which you
can serialize your object just by calling their Serialize() and Deserialize() methods.
There is a serious security issue connected with serialization. You might not want certain classes to be serialized to
the stream or you might not want to serialize all of your member variables to the stream. For example, a
web-application may not allow the UserInfo object to be serialized or its Password field to be serialized.
All the classes in .Net are un-serializable by default - that is they can not be written to a stream. You have to
explicitly mark your class to be serializable using the [Serializable] attribute.
You can optionally mark a particular member variable (or field) as Non-Serialized by using the [NonSerialized]
attribute to prevent the CLR from writing that field when serializing the object.

Implementing Serialization and Deserialization – A simple example

using System;
using System.IO; // for FileStream
using System.Runtime.Serialization.Formatters.Binary; // for BinaryFormatter
namespace Compiler
{
class Test
{
static void Main()
{
Addition addition = new Addition(3, 4);
FileStream fs = new FileStream(@"C:\C-Sharp.txt", FileMode.Create);
BinaryFormatter binForm = new BinaryFormatter();
Console.WriteLine("Serializing the object....");
binForm.Serialize(fs, addition);
fs.Position = 0; // move to the start of file
Console.WriteLine("DeSerializing the object....");
Addition sum = (Addition) binForm.Deserialize(fs);
int res = sum.Add();
Console.WriteLine("The sum of 3 and 4 is: {0}", res);
}
}
[Serializable]
class Addition
{
private int num1;
private int num2;
private int result;
public Addition()
{
}
public Addition(int num1, int num2)
{
this.num1 = num1;
this.num2 = num2;
}
public int Add()
{
result = num1 + num2;
return result;
}

Reflecting an Assembly (Loading DLL using reflection at runtime in C#)

Reflection is the ability to find out information about objects, the application details (assemblies), its metadata at run-time.

Assembly a = Assembly.LoadFile(@"c:\Business.dll");
Response.Write("Location **** "+a.CodeBase);
Response.Write("
EntryPoint **** " + a.EntryPoint);
Response.Write("
FullName **** " + a.FullName);

Type[] types = a.GetTypes();
foreach (Type t in types)
{
Response.Write("
Type is {0} " + t);
}

Saturday, November 21, 2009

C# Interview Questions(Faq's) on Access Modifiers

What are Access Modifiers in C#?
In C# there are 5 different types of Access Modifiers.
Public
The public type or member can be accessed by any other code in the same assembly or another assembly that references it.

Private
The type or member can only be accessed by code in the same class or struct.

Protected
The type or member can only be accessed by code in the same class or struct, or in a derived class.

Internal
The type or member can be accessed by any code in the same assembly, but not from another assembly.

Protected Internal
The type or member can be accessed by any code in the same assembly, or by any derived class in another assembly.

What are Access Modifiers used for?
Access Modifiers are used to control the accessibilty of types and members with in the types.

Can you use all access modifiers for all types?
No, Not all access modifiers can be used by all types or members in all contexts, and in some cases the accessibility of a type member is constrained by the accessibility of its containing type.

Can derived classes have greater accessibility than their base types?
No, Derived classes cannot have greater accessibility than their base types. For example the following code is illegal.
using System;
internal class InternalBaseClass
{
public void Print()
{
Console.WriteLine("I am a Base Class Method");
}
}
public class PublicDerivedClass : InternalBaseClass
{
public static void Main()
{
Console.WriteLine("I am a Public Derived Class Method");
}
}

When you compile the above code an error will be generated stating "Inconsistent accessibility: base class InternalBaseClass is less accessible than class PublicDerivedClass".To make this simple, you cannot have a public class B that derives from an internal class A. If this were allowed, it would have the effect of making A public, because all protected or internal members of A are accessible from the derived class.


Is the following code legal?

using System;
private class Test
{
public static void Main()
{
}
}

No, a compile time error will be generated stating "Namespace elements cannot be explicitly declared as private, protected, or protected internal"

Can you declare struct members as protected?

No, struct members cannot be declared protected. This is because structs do not support inheritance.

Can the accessibility of a type member be greater than the accessibility of its containing type?
No, the accessibility of a type member can never be greater than the accessibility of its containing type. For example, a public method declared in an internal class has only internal accessibility.

Can destructors have access modifiers?
No, destructors cannot have access modifiers.

What does protected internal access modifier mean?
The protected internal access means protected OR internal, not protected AND internal. In simple terms, a protected internal member is accessible from any class in the same assembly, including derived classes. To limit accessibility to only derived classes in the same assembly, declare the class itself internal, and declare its members as protected.

What is the default access modifier for a class,struct and an interface declared directly with a namespace?

internal

Will the following code compile?

using System;
interface IExampleInterface
{
public void Save();
}

No, you cannot specify access modifer for an interface member. Interface members are always public.

Can you specify an access modifier for an enumeration?
Enumeration members are always public, and no access modifiers can be specified.

C# Interview Questions on Properties

What are Properties in C#. Explain with an example?
Properties in C# are class members that provide a flexible mechanism to read, write, or compute the values of private fields. Properties can be used as if they are public data members, but they are actually special methods called accessors. This enables data to be accessed easily and still helps promote the safety and flexibility of methods.

In the example below _firstName and _lastName are private string variables which are accessible only inside the Customer class. _firstName and _lastName are exposed using FirstName and LastName public properties respectively. The get property accessor is used to return the property value, and a set accessor is used to assign a new value. These accessors can have different access levels. The value keyword is used to define the value being assigned by the set accessor. The FullName property computes the full name of the customer. Full Name property is readonly, because it has only the get accessor. Properties that do not implement a set accessor are read only.

The code block for the get accessor is executed when the property is read and the code block for the set accessor is executed when the property is assigned a new value.


using System;
class Customer
{
// Private fileds not accessible outside the class.
private string _firstName = string.Empty;
private string _lastName = string.Empty;
private string _coutry = string.Empty;

// public FirstName property exposes _firstName variable
public string FirstName
{
get
{
return _firstName;
}
set
{
_firstName = value;
}
}
// public LastName property exposes _lastName variable
public string LastName
{
get
{
return _lastName;
}
set
{
_lastName = value;
}
}
// FullName property is readonly and computes customer full name.
public string FullName
{
get
{
return _lastName + ", " + _firstName;
}
}
//Country Property is Write Only
public string Country
{
set
{
_coutry = value;
}
}

}
class MainClass
{
public static void Main()
{
Customer CustomerObject = new Customer();
//This line will call the set accessor of FirstName Property
CustomerObject.FirstName = "David";
//This line will call the set accessor of LastName Property
CustomerObject.LastName = "Boon";
//This line will call the get accessor of FullName Property
Console.WriteLine("Customer Full Name is : " + CustomerObject.FullName);
}
}

Explain the 3 types of properties in C# with an example?
1. Read Only Properties: Properties without a set accessor are considered read-only. In the above example FullName is read only property.
2. Write Only Properties: Properties without a get accessor are considered write-only. In the above example Country is write only property.
3. Read Write Properties: Properties with both a get and set accessor are considered read-write properties. In the above example FirstName and LastName are read write properties.

What are the advantages of properties in C#?
1. Properties can validate data before allowing a change.
2. Properties can transparently expose data on a class where that data is actually retrieved from some other source such as a database.
3. Properties can take an action when data is changed, such as raising an event or changing the value of other fields.

What is a static property. Give an example?
A property that is marked with a static keyword is considered as static property. This makes the property available to callers at any time, even if no instance of the class exists. In the example below PI is a static property.

using System;
class Circle
{
private static double _pi = 3.14;
public static double PI
{
get
{
return _pi;
}
}
}
class MainClass
{
public static void Main()
{
Console.WriteLine(Circle.PI);
}
}

What is a virtual property. Give an example?
A property that is marked with virtual keyword is considered virtual property. Virtual properties enable derived classes to override the property behavior by using the override keyword. In the example below FullName is virtual property in the Customer class. BankCustomer class inherits from Customer class and overrides the FullName virtual property. In the output you can see the over riden implementation. A property overriding a virtual property can also be sealed, specifying that for derived classes it is no longer virtual.


using System;
class Customer
{
private string _firstName = string.Empty;
private string _lastName = string.Empty;

public string FirstName
{
get
{
return _firstName;
}
set
{
_firstName = value;
}
}
public string LastName
{
get
{
return _lastName;
}
set
{
_lastName = value;
}
}
// FullName is virtual
public virtual string FullName
{
get
{
return _lastName + ", " + _firstName;
}
}
}
class BankCustomer : Customer
{
// Overiding the FullName virtual property derived from customer class
public override string FullName
{
get
{
return "Mr. " + FirstName + " " + LastName;
}
}
}
class MainClass
{
public static void Main()
{
BankCustomer BankCustomerObject = new BankCustomer();
BankCustomerObject.FirstName = "David";
BankCustomerObject.LastName = "Boon";
Console.WriteLine("Customer Full Name is : " + BankCustomerObject.FullName);
}
}

What is an abstract property. Give an example?
A property that is marked with abstract keyword is considered abstract property. An abstract property should not have any implementation in the class. The derived classes must write their own implementation. In the example below FullName property is abstract in the Customer class. BankCustomer class overrides the inherited abstract FullName property with its own implementation.


using System;
abstract class Customer
{
private string _firstName = string.Empty;
private string _lastName = string.Empty;

public string FirstName
{
get
{
return _firstName;
}
set
{
_firstName = value;
}
}
public string LastName
{
get
{
return _lastName;
}
set
{
_lastName = value;
}
}
// FullName is abstract
public abstract string FullName
{
get;
}
}
class BankCustomer : Customer
{
// Overiding the FullName abstract property derived from customer class
public override string FullName
{
get
{
return "Mr. " + FirstName + " " + LastName;
}
}
}
class MainClass
{
public static void Main()
{
BankCustomer BankCustomerObject = new BankCustomer();
BankCustomerObject.FirstName = "David";
BankCustomerObject.LastName = "Boon";
Console.WriteLine("Customer Full Name is : " + BankCustomerObject.FullName);
}
}

Can you use virtual, override or abstract keywords on an accessor of a static property?
No, it is a compile time error to use a virtual, abstract or override keywords on an accessor of a static property.

C# Interview Questions on value types and reference types

What are the 2 types of data types available in C#?
1. Value Types
2. Reference Types

If you define a user defined data type by using the struct keyword, Is it a a value type or reference type?
Value Type

If you define a user defined data type by using the class keyword, Is it a a value type or reference type?
Reference type

Are Value types sealed?
Yes, Value types are sealed.

What is the base class from which all value types are derived?
System.ValueType

Give examples for value types?
Enum
Struct

Give examples for reference types?

Class
Delegate
Array
Interface

What are the differences between value types and reference types?
1. Value types are stored on the stack where as reference types are stored on the managed heap.
2. Value type variables directly contain their values where as reference variables holds only a reference to the location of the object that is created on the managed heap.
3. There is no heap allocation or garbage collection overhead for value-type variables. As reference types are stored on the managed heap, they have the over head of object allocation and garbage collection.
4. Value Types cannot inherit from another class or struct. Value types can only inherit from interfaces. Reference types can inherit from another class or interface.

C Sharp interview questions (FAQ'S) on Struct

Will the following code compile?
using System;
public class Example
{
static void Main()
{
TestStruct T = new TestStruct();
Console.WriteLine(T.i);
}
}
public struct TestStruct
{
public int i=10;
//Error: cannot have instance field initializers in structs
}
No, a compile time error will be generated stating "within a struct declaration, fields cannot be initialized unless they are declared as const or static"

Can a struct have a default constructor (a constructor without parameters) or a destructor in C#?
No

Can you instantiate a struct without using a new operator in C#?
Yes, you can instantiate a struct without using a new operator

Can a struct inherit from another struct or class in C#?
No, a struct cannot inherit from another struct or class, and it cannot be the base of a class.

Can a struct inherit from an interface in C#?
Yes

Are structs value types or reference types?
Structs are value types.

What is the base type from which all structs inherit directly?
All structs inherit directly from System.ValueType, which inherits from System.Object.

C Sharp interview questions - part 2

Give Some Examples of Generic Classes?
List,Queue,Stack,LinkedList,HashSet

Generic Collections are located in which NameSpace?
System.Collections.Generic

Object type collections are located in the which NameSpace?
System.Collections

What does the modifier protected internal in C# mean?
The Protected Internal can be accessed by Members of the Assembly or the inheriting class, and of course, within the class itself.

What is the Global.asax used for?
The Global.asax (including the Global.asax.cs file) is used to implement application and session level events.

What are the Application_Start and Session_Start subroutines used for?
This is where you can set the specific variables for the Application and Session objects.

How many classes can a single .NET DLL contain?
It can contain many classes.

What base class do all Web Forms inherit from?
The Page class.

What’s the .NET datatype that allows the retrieval of data by a unique key?
Ans. HashTable.

Can you edit data in the Repeater control?
No, it just reads the information from its data source.

When during the page processing cycle is ViewState available?
After the Init() and before the Page_Load(), or OnLoad() for a control.

What’s class SortedList underneath?
Ans. A sorted HashTable.