Saturday, July 12, 2008

ACCESS SPECIFIERS, Constructor, Destructor

ACCESS SPECIFIERS

What are the access-specifiers available in c#?

Private, Protected, Public, Internal, Protected Internal, static

[VB.Net/C#]
Public/public All members in all classes and projects.

Private/private Members of the current class only.

Friend/internal All members in the current project.

Protected/protected All members in the current class and in classes derived from this member’s class. Can be used only in member definitions, not for class or module definitions.

Protected Friend/protected internal All members in the current project and all members in classes derived from this member’s class. Can be used only in member definitions, not for class or module definitions.

Explain about Protected and protected internal, “internal” access-specifier?

protected - Access is limited to the containing class or types derived from the containing class.
internal - Access is limited to the current assembly.
protected internal - Access is limited to the current assembly or types derived from the containing class.

If it is protected internal, we can inherit the class from out side of the assemply and access the protected internal member we can not access the internal member.


CONSTRUCTOR DESTRUCTOR

Static constructor
Will execute before the first instance was created. It will be accesable for all the instance.

Copy constructor
Copy constructor is just like over loaded constructor but the paramenter is the class which the constructor is belongs.

Private constructor

If the constructor is private constructor, which will not allow to create the instance for the class.
But using the static function we can achive the singleton pattern, mean the we can control the number of the instance of the class. Or we can control the number of the instance of the class.

Explain constructor?

Difference between type constructor and instance constructor? What is static constructor, when it will be fired? And what is its use?

(Class constructor method is also known as type constructor or type initializer)
Instance constructor is executed when a new instance of type is created and the class constructor is executed after the type is loaded and before any one of the type members is accessed. (It will get executed only 1st time, when we call any static methods/fields in the same class.) Class constructors are used for static field initialization. Only one class constructor per type is permitted, and it cannot use the vararg (variable argument) calling convention.
A static constructor is used to initialize a class. It is called automatically to initialize the class before the first instance is created or any static members are referenced.

Static Constructor in C# and their Usages

C# supports two types of constructor, a class constructor (static constructor) and an instance constructor (non-static constructor).

Static constructor is used to initialize static data members as soon as the class is referenced
first time, whereas an instance constructor is used to create an instance of that class with
keyword. A static constructor does not take access modifiers or have parameters and can't access any non-static data member of a class.

Since static constructor is a class constructor, they are guaranteed to be called as soon as we refer to that class or by creating an instance of that class.

You may say, why not initialize static data members where we declare them in the code. Like this :

private static int id = 10;
private static string name = "jack";

Static data members can certainly be initialized at the time of their declaration but there are times when value of one static member may depend upon the value of another static member. In such cases we definitely need some mechanism to handle conditional initialization of static members. To handlesuch situation, C# provides static constructor.

Let me explain you with examples :

//File Name : Test.cs

using System;

namespace Constructor
{

class Test
{
//Declaration and initialization of static data member
private static int id = 5;

public static int Id
{
get
{
return id;
}
}

public static void print()
{
Console.WriteLine("Test.id = " + id);
}

static void Main(string[] args)
{

//Print the value of id
Test.print();
}
}

}

In the above example, static data member is declared and initialized in same line. So if you compile and run this program your output would look similar to this :

Test.id = 5

Lets create one more class similar to class Test but this time the value of its static data member would depend on the value of static data member of class Test.id.

//File Name : Test1.cs
using System;

namespace Constructor
{

class Test1
{
private static int id ;

//Static constructor, value of data member id is set conditionally here.
//This type of initialization is not possible at the time of declaration.
static Test1()
{
if( Test.Id < 10 )
{
id = 20;
}
else
{
id = 100;
}

Console.WriteLine("Static Constructor for Class Test1 Called..");
}

public static void print()
{
Console.WriteLine("Test1.id = " + id);
}

static void Main(string[] args)
{

//Print the value of id
Test1.print();
}

}
}

As you can see in the above static constructor, static data member is initialized conditionally. This type of initialization is not possible at the time of declaration. This is where static constructor comes in picture. So if you compile and run this program your output would look similar to this :

Static Constructor for Class Test1 Called..
id = 20

Since in class Test was initialized with a value of 5, therefore in class Test1 got initialized to a value of 20.


Some important point regarding static constructor from C# Language Specification and C# Programmer's Reference :

1) The static constructor for a class executes before any instance of the class is created.
2) The static constructor for a class executes before any of the static members for the class are referenced.
3) The static constructor for a class executes after the static field initializers (if any) for the class.
4) The static constructor for a class executes at most one time during a single program instantiation
5) A static constructor does not take access modifiers or have parameters.
6) A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.
7) A static constructor cannot be called directly.
8) The user has no control on when the static constructor is executed in the program.
9) A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.


What is Private Constructor? and it’s use? Can you create instance of a class which has Private Constructor?

A: When a class declares only private instance constructors, it is not possible for classes outside the program to derive from the class or to directly create instances of it. (Except Nested classes)
Make a constructor private if:
- You want it to be available only to the class itself. For example, you might have a special constructor used only in the implementation of your class' Clone method.
- You do not want instances of your component to be created. For example, you may have a class containing nothing but Shared utility functions, and no instance data. Creating instances of the class would waste memory.

I have 3 overloaded constructors in my class. In order to avoid making instance of the class do I need to make all constructors to private?

yes

Overloaded constructor will call default constructor internally?
no

What are virtual destructors?

Destructor and finalize

Generally in C++ the destructor is called when objects gets destroyed. And one can explicitly call the destructors in C++. And also the objects are destroyed in reverse order that they are created in. So in C++ you have control over the destructors.

In C# you can never call them, the reason is one cannot destroy an object. So who has the control over the destructor (in C#)? it's the .Net frameworks Garbage Collector (GC). GC destroys the objects only when necessary. Some situations of necessity are memory is exhausted or user explicitly calls System.GC.Collect() method.

Points to remember:

1. Destructors are invoked automatically, and cannot be invoked explicitly.
2. Destructors cannot be overloaded. Thus, a class can have, at most, one destructor.
3. Destructors are not inherited. Thus, a class has no destructors other than the one, which may be declared in it.
4. Destructors cannot be used with structs. They are only used with classes.
5. An instance becomes eligible for destruction when it is no longer possible for any code to use the instance.
6. Execution of the destructor for the instance may occur at any time after the instance becomes eligible for destruction.
7. When an instance is destructed, the destructors in its inheritance chain are called, in order, from most derived to least derived.
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconfinalizemethodscdestructors.asp

No comments: