output.newplans.comoutput.newplans.com/Outputs/Project_14488/ProjectDoc…  · Web viewObserve...

24

Click here to load reader

Transcript of output.newplans.comoutput.newplans.com/Outputs/Project_14488/ProjectDoc…  · Web viewObserve...

Page 1: output.newplans.comoutput.newplans.com/Outputs/Project_14488/ProjectDoc…  · Web viewObserve that the function Main in zzz is static. This is because we are not creating any object

1

Constructors and DestructorsNew

Let's consider the following program.a.csclass zzz { static void Main() { yyy.abc(); } }

class yyy { public void abc() { System.Console.WriteLine("abc"); } }

Compiler Errora.cs(5,1) : error CS0120: An object reference is required for the nonstatic field, method or property 'yyy.abc()'

This program contains one class called yyy which has a function called abc. In Main() we are using the syntax yyy.abc() to call the abc function as we did earlier. Within the abc function we have the code for the function abc that will print the string "abc". On compiling this program you will get an error.

But how is it that when we ran this program earlier we didn't get an error? If you are still bewildered, wake up and smell the coffee! Didn't you notice we removed the word 'static' while saying public void abc(). Hence we get an error.

In our earlier programs when we wrote the function abc we had written the word static which is missing now.

No, we are not going to tell you to add the word static and execute the program. We shall do something quite different and interesting. Keeping that in mind let's consider the next program.

Function abc doesn’t have a static keyword and so while calling, it displays error.

Note: If we instantiate then it will not show an error

yyy a = new yyy();a.abc();

This will call and run the abc() function.

Page 2: output.newplans.comoutput.newplans.com/Outputs/Project_14488/ProjectDoc…  · Web viewObserve that the function Main in zzz is static. This is because we are not creating any object

2

a.csclass zzz { static void Main() { yyy a; a.abc(); } }

class yyy { public void abc() { System.Console.WriteLine("abc"); } }

Compiler Errora.cs(6,1): error CS0165: Use of unassigned local variable 'a'

Before we look into this program let's get our basics clear. We have often used the statement 'int i' meaning that i was a variable that looked like an int. When we used the statement 'string s', it meant that s was a variable that looked like string. Similarly, in this program we are saying yyy a. This implies that 'a' looks like yyy. What is yyy? It is the name of a class. Here we do not call 'a' a variable, we call it an object. An object and a variable can be used interchangeably.

Earlier, whenever we wanted to call a member from a class we would say yyy.abc(); i.e. class name dot function name. But in our current program we are saying a.abc(); We are using the same dot, but now it gives an error saying - 'Use of unassigned local variable'.

But things still don't seem any clearer. So, let's go a step further and add another statement a=new yyy(); Match your code with the one below.

Page 3: output.newplans.comoutput.newplans.com/Outputs/Project_14488/ProjectDoc…  · Web viewObserve that the function Main in zzz is static. This is because we are not creating any object

3

a.csclass zzz { static void Main() { yyy a; a=new yyy(); a.abc(); } }

class yyypg. 3 { public void abc() { System.Console.WriteLine("abc"); } }Outputabc

The word or keyword new must be followed by the name of a class; You cannot substitute it with anything else, it must be a class. In our case, we have given the statement as new yyy(). yyy is the name of an existing class.

Thus it is at this point i.e. after saying new, that the object 'a' that looks like yyy is created. We could have also called the object 'a' an instance of the class yyy. Since the class yyy has only one function it will allocate memory for THAT one function ONLY. Now we have an object 'a' that looks like class yyy. Once the object is created, it can be used to access the function from class yyy. Hence, now if we say a.abc() we will not get an error.

Thus an object is nothing but an instance or an occurrence of a class. Therefore, 'a' is an instance of the class yyy. This is how you can instantiate an object.

In order to create an object you must use the keyword 'new'. Our next program will help you gain a better understanding of this concept.

Page 4: output.newplans.comoutput.newplans.com/Outputs/Project_14488/ProjectDoc…  · Web viewObserve that the function Main in zzz is static. This is because we are not creating any object

4

a.csclass zzz { static void Main() { int i; i=new int(); } }

At first we have int i, meaning i looks like int. Then we have i=new int(); Executing this program will not generate any errors. But so far whenever we used int i we never created the object i using new int(). This is because C# does this internally for us. It saves us the trouble of doing so. Then why doesn't C# do so for all the other objects that we create? This is because C# recognizes only two types of classes.

The first type is one that the C# compiler knows of in advance. int, long, bool, and string are classes that fall into this category. These are predefined classes. But we call them data types because in C and C++ they were called data types and C# has a legacy of C and C++. So technically, when we say int i it does i=new int(); internally.

The second type of classes that C# recognizes are the ones that we create i.e. user-defined classes. For user-defined classes we have to create objects ourselves. Thus anything other than the basic data-types must be explicitly created.

So when we say 'yyy a' we are not creating the object at this point. We are only declaring the object to be of type yyy. It is only when we use the word 'new' that the object is created and memory is allocated for the same. Therefore, when we have our own classes, that's the time we use new. Without new you cannot create an object.

Static

You are certainly going to benefit by the patience you have shown so far. To find out how, let's follow the next program.

Page 5: output.newplans.comoutput.newplans.com/Outputs/Project_14488/ProjectDoc…  · Web viewObserve that the function Main in zzz is static. This is because we are not creating any object

5

a.csclass zzz { static void Main() { yyy a; a=new yyy(); a.abc(); yyy.pqr(); } }

class yyy { public void abc() { System.Console.WriteLine("abc"); } public static void pqr() { System.Console.WriteLine("pqr"); } }

Outputabcpqr

In this program we have two functions abc and pqr. The function pqr has the word static whereas abc does not. If you want to access the static function pqr you say yyy.pqr() and to access the non static function abc you say a.abc(); You can't do the reverse i.e. you cant say a.pqr() and yyy.abc().

If the function has a static keyword then call the by specifying className. function Name like yyy.pqr().

Note: We can’t create an object for static function

Page 6: output.newplans.comoutput.newplans.com/Outputs/Project_14488/ProjectDoc…  · Web viewObserve that the function Main in zzz is static. This is because we are not creating any object

6

a.csclass zzz { static void Main() { yyy a =new yyy(); yyy.abc(); a.pqr(); } }

class yyy { public void abc() { System.Console.WriteLine("abc"); } public static void pqr() { System.Console.WriteLine("pqr"); } }

Compiler Errora.cs(7,1): error CS0120: An object reference is required for the nonstatic field, method, or property 'yyy.abc()'a.cs(8,1): error CS0176: Static member 'yyy.pqr()' cannot be accessed with an instance reference; qualify it with a type name instead

The word 'static' implies 'free'. Static signifies that you can access a member or a function without creating an object.

Observe that the function Main in zzz is static. This is because we are not creating any object that looks like zzz. The crux (bottom line) is that if you don't want to use 'new' and yet use the function then you must make the function static.

In both cases a dot is used to reference the function. The only difference is that a static member belongs to the class and as such we don't need to create an object to access it. On the other hand, a non-static member, that is the default, can be accessed only via an object of the class. Thus WriteLine is a static function in Console as we did not create an object that looks like Console to access it.

Page 7: output.newplans.comoutput.newplans.com/Outputs/Project_14488/ProjectDoc…  · Web viewObserve that the function Main in zzz is static. This is because we are not creating any object

7

a.csclass zzz { static void Main() { System.Console.WriteLine(yyy.i); } }

class yyy { public int i = 10; }

Compiler Errora.cs(5,26): error CS0120: An object reference is required for the nonstatic field, method, or property 'yyy.i'

Why did we get an error? Think!!! If you still haven't got it, let us tell you. The same rules for static apply to functions as well as variables. Hence we get the above error.

a.csclass zzz { static void Main() { yyy a = new yyy(); yyy b = new yyy(); a.j = 11; System.Console.WriteLine(a.j); System.Console.WriteLine(b.j); yyy.i = 30; System.Console.WriteLine(yyy.i); } }

Output111030

A static variable belongs to the class. Hence if we create a static variable i, no matter how many objects we create that look like yyy, there will be one and only one value of i as there is only one variable i created in memory. Thus we access a static variable by prefacing with the name

class yyy{public static int i = 10;public int j = 10;}

Variable i is not mention static

Page 8: output.newplans.comoutput.newplans.com/Outputs/Project_14488/ProjectDoc…  · Web viewObserve that the function Main in zzz is static. This is because we are not creating any object

8

of the class and not name of object. If the variable is non-static like j then we have to use the syntax as explained earlier i.e. name of object dot name of variable. Thus each time we create an object that looks like yyy we are creating a new/another copy of the variable j in memory. We now have two j's in memory one for a and another for b. Thus j is called an instance variable unlike i. When we change the variable j of a to 11, the j of b remain at 10.

Thus functions are created in memory only once, irrespective of the word static. If a class has no instance or non static variables then it makes no sense to create multiple instances of the object as there will be no way of distinguishing between the copies created.

Constructors

a.csclass zzz { public static void Main() { yyy a; System.Console.WriteLine("Main"); a=new yyy(); } }

class yyy { public yyy() { System.Console.WriteLine("yyy"); } }OutputMainyyy

In the above program we have a class called yyy. We also have a function called yyy which happens to be having the same name as the name of the class. We have a friend named Bunty. Coincidentally, the name of his pet dog is also Bunty! Similarly, it is absolutely legal to have a function by the same name as that of the class. In this case first we see Main and then we see yyy displayed on the screen which means that the function yyy() gets called automatically. Note, we have not called the function yyy explicitly.

This happens to be a special function and it is called a 'constructor'.

Page 9: output.newplans.comoutput.newplans.com/Outputs/Project_14488/ProjectDoc…  · Web viewObserve that the function Main in zzz is static. This is because we are not creating any object

9

Initially we are saying yyy a. By doing so we are specifying that 'a' looks like yyy. We are not creating an object that looks like yyy. The next statement has System.Console.WriteLine, which will print 'Main'. Thereafter, using new we are creating an object a. It is at this point that C# calls the constructor i.e. it calls the function yyy(). Now you will see 'yyy' displayed. This goes to prove that as soon as an object of a class is created, C# automatically calls the constructor. A constructor gets called at the time of birth or creation of the object. It has to have the same name as the name of the class.

a.csclass zzz { public static void Main() { yyy a; System.Console.WriteLine("Main"); a=new yyy(); a.yyy(); }}

class yyy { public yyy() { System.Console.WriteLine("yyy"); }}

Compiler Errora.cs(8,1): error CS0117: 'yyy' does not contain a definition for 'yyy'

Here, we are calling the function yyy using the appropriate syntax i.e. by saying a.yyy(). Now, run the compiler. Baffled by the error? The error says 'yyy' does not contain a definition for 'yyy'. The class yyy does contain a function called yyy which got called in the previous example. Has C# developed amnesia all of a sudden? What went wrong? Well, you cannot call this function using a.yyy() or yyy.yyy() The catch is that when you have a function with the same name as that of the class you cannot call it at all. It gets called automatically. C# does not give anyone the authority to call such a function. It calls this function automatically only at birth. Seems abnormal doesn't it!

But what is the purpose of having constructors?

A constructor can be used in cases where every time an object gets created and you want some code to be automatically executed. The code that you want executed must be put in the

Page 10: output.newplans.comoutput.newplans.com/Outputs/Project_14488/ProjectDoc…  · Web viewObserve that the function Main in zzz is static. This is because we are not creating any object

10

constructor. That code could be anything, it could check for hard disk space, it could create a file or it could connect to the net and bring a file over. What that code will do shall vary from person to person.

To understand how and when the constructor gets called, let's take into consideration our next example. Now remove the word 'public' in front of yyy() as we have done below.

a.csclass zzz { public static void Main() { yyy a; System.Console.WriteLine("hi"); a=new yyy(); } }

class yyy { yyy() { System.Console.WriteLine("yyy const"); }}

Compiler Errora.cs(7,3): error CS0122: 'yyy.yyy()' is inaccessible due to its protection level.

Obviously, you will get an error. This is because without the word public the function is private property. And when you trespass on private property you have to face the consequences. In our case we are faced with an error. By making the function public every one can use it, it is now becomes public property! If the constructor is private then nobody can create an object that looks like yyy.

Do you think constructors can return values? Let's try it out and find out for ourselves.

Page 11: output.newplans.comoutput.newplans.com/Outputs/Project_14488/ProjectDoc…  · Web viewObserve that the function Main in zzz is static. This is because we are not creating any object

11

a.csclass zzz { public static void Main() { yyy a; System.Console.WriteLine("hi"); a=new yyy(); }}

class yyy { public int yyy() { System.Console.WriteLine("yyy const"); }}

Compiler Errora.cs(12,12): error CS0542: 'yyy': member names cannot be the same as their enclosing type

Executing the above program generates an error. It says that member i.e yyy cannot be the same as the enclosing type i.e class yyy. Now, that is an error that you certainly didn't expect.

Let us analyze why we got this error.

Here we are saying public int yyy implying that the function yyy() is returning an int. yyy() is a constructor and is called automatically at the time an object is created. If a constructor is to return a value then to whom should it return the value to? Since it is called automatically, there is nothing that can accept the return value. Thus constructors cannot return values. Also when a constructor gets called, an object is in the act of being created. It has not yet been created. The keyword new first allocates memory for the functions and the variables. After this it calls the constructor. When the constructor finishes, then we say that the object has been created. Thus the constructor has no one to return values to.

Now that we know constructors don't return values let's return void instead.

Page 12: output.newplans.comoutput.newplans.com/Outputs/Project_14488/ProjectDoc…  · Web viewObserve that the function Main in zzz is static. This is because we are not creating any object

12

a.csclass zzz { public static void Main() { yyy a; System.Console.WriteLine("hi"); a=new yyy(); } }

class yyy { public void yyy() { System.Console.WriteLine("yyy const"); } }

Compiler Errora.cs(12,13): error CS0542: 'yyy': member names cannot be the same as their enclosing type

Though we are returning void, we get the same error. This is because C# is very sure of what it says. When you borrow from other people you do so on the pretext that you will return it. It's a different story that you never do! You rarely mean what you say. But when C# says that constructors cannot return values it means 'constructors cannot return values', not even 'void'. Remember, there is nothing that can accept the return values. Hence even void cannot be accepted. When a function returns a void we mean that it will return no value at all. For a constructor, the word return makes no sense at all.

Page 13: output.newplans.comoutput.newplans.com/Outputs/Project_14488/ProjectDoc…  · Web viewObserve that the function Main in zzz is static. This is because we are not creating any object

13

Constructors with parameters

Just as we pass parameters to other functions, you can also pass parameters to constructors.

a.csclass zzz { public static void Main() { yyy a; System.Console.WriteLine("hi"); a=new yyy("no"); } }

class yyy { public yyy() { System.Console.WriteLine("yyy const"); } }

Compiler Errora.cs(7,3): error CS1501: No overload for method 'yyy' takes '1' arguments

You are already aware of the fact that parameters are passed to functions while calling them. Similarly, we will pass a parameter to the constructor yyy while creating the object a; because it is at this point that the constructor gets called.

Hence we are saying a=new yyy("no"). But on compiling this program you get an error. Here, the constructor is being called with a string 'no' as a parameter. But there is no variable in the constructor yyy to store the value 'no'. Add 'string s' in the constructor yyy and watch the error disappear.

Page 14: output.newplans.comoutput.newplans.com/Outputs/Project_14488/ProjectDoc…  · Web viewObserve that the function Main in zzz is static. This is because we are not creating any object

14

a.csclass zzz { public static void Main() { yyy a; System.Console.WriteLine("hi"); a=new yyy("no"); } }

class yyy { public yyy(string s) { System.Console.WriteLine(s); } }

Outputhino

At first WriteLine will display 'hi'. Then we have a constructor yyy that takes a string 'no' as a parameter and accepts it in a variable s. Thus the moment the constructor yyy is called 'no' will be displayed. This is because the constructor yyy contains code that will print the value stored in the variable s. This is how constructors with parameters are called.

So far we created only one instance of the class yyy. In the following program we are creating two instances of the class yyy, 'a' and 'b'.

Page 15: output.newplans.comoutput.newplans.com/Outputs/Project_14488/ProjectDoc…  · Web viewObserve that the function Main in zzz is static. This is because we are not creating any object

15

a.csclass zzz { public static void Main() { yyy a,b; System.Console.WriteLine("hi"); a=new yyy("no"); b=new yyy(); } }

Compiler Errora.cs(8,3): error CS1501: No overload for method 'yyy' takes '0' arguments

While creating the object 'a' the constructor yyy is being passed a parameter 'hi'. In case of the object 'b' the constructor will be called without any parameters. But in our program we have code only for the constructor with parameters. Try executing this program and you will get an error saying that method yyy takes 0 arguments. This is because we do not have code for the constructor without parameters.

Let's understand the reason behind the error.

In our earlier programs, we did not specify a constructor. A relevant question here would be - how did the objects get created then, without the constructor being called? C# is a Good Samaritan, at that time it inserted a free constructor. It does so internally. On its own it inserts a constructor without any parameters, without any code into the class.

It looks like this-

yyy(){}

Point to ponder - in the above program, when we didn't create a constructor without parameters why didn't we get one free? Remember we said C# is a Good Samaritan? And Good Samaritans help the needy. On seeing that we already have a constructor with parameters, C# looks the other way i.e., it takes the free one away. However, it is only when you have no constructor at all that C# melts its heart and gives you one free. Remember, even if it finds that you have even one constructor it will take away the free one. On the assumption that if you can provide one constructor, then with a little effort you can work towards providing the others too!

Now the only way to get rid of the error is to add the constructor yourself.

class yyy { public yyy(string s) { System.Console.WriteLine(s); } }

Page 16: output.newplans.comoutput.newplans.com/Outputs/Project_14488/ProjectDoc…  · Web viewObserve that the function Main in zzz is static. This is because we are not creating any object

16

a.csclass zzz { public static void Main() { yyy a,b; System.Console.WriteLine("hi"); a=new yyy("no"); b=new yyy(); } }

class yyy { public yyy(string s) { System.Console.WriteLine(s); } public yyy() { System.Console.WriteLine("bad"); } }

Outputhinobad

Here, initially, the two objects 'a' and 'b' are declared. In the next statement we have WriteLine, which will display 'hi'. We are then creating the object a. At this point the constructor with a string as a parameter is called. It will now display the value stored in the variable s which is 'no'. Thereafter, the object b is created. At this point the constructor without the parameters will be called. This constructor contains the WriteLine statement, which will print 'bad'. Here, we have as many constructors as we are calling and hence we do not get any errors.

So, essentially, a constructor is a special function that gets called when an object is created. It does not return any values, not even void. As far as parameters go it behaves like a normal function. If no constructors are specified you get one free, otherwise, you need as many constructors as you are calling. Hence in the above case we cannot create an object as new yyy(100) as we do not have a constructor that accepts one int as a parameter.

Page 17: output.newplans.comoutput.newplans.com/Outputs/Project_14488/ProjectDoc…  · Web viewObserve that the function Main in zzz is static. This is because we are not creating any object

17

Destructors

a.cspublic class zzz { public static void Main() { aa a = new aa(); } }

public class aa { public aa() { System.Console.WriteLine("Constructor "); } ~aa() { System.Console.WriteLine("Destructor"); } }

OutputConstructorDestructor

A destructor is a function with the same name as the name of a class but starting with the character ~. A constructor gets called at birth whereas a destructor gets called at death. In C# unlike other languages we do not know when an object dies as unlike James Bond, we do not have a license to kill. Thus even though the object a dies at the end of main, the destructor may not get called. Thus, in C# we cannot decide when the destructor gets called. This decision to call the destructor is made by a program within C# called the garbage collector.

The concept first gained currency with the advent of Java. In Java and C# we cannot remove our objects from memory. Thus it is for the garbage collector to decide when to call the destructor. The programming world was replete with errors mainly because programmers use new to allocate memory and then forget to deallocate it. This gave rise to a concept called memory leaks. On the flip side of the coin, programmers deallocated the memory, forgot about it and then accessed the object again. This generates an error occurring at random and difficult to pin down.

Page 18: output.newplans.comoutput.newplans.com/Outputs/Project_14488/ProjectDoc…  · Web viewObserve that the function Main in zzz is static. This is because we are not creating any object

18

a.cspublic class zzz { public static void Main() { aa a = new aa(); } }

Compiler Errora.cs(14,9): error CS0106: The modifier 'public' is not valid for this item

A destructor cannot have any modifiers like public preceding it. a.cspublic class zzz { public static void Main() { aa a = new aa(); } }

Compiler Errora.cs(14,5): error CS1026: ) expecteda.cs(14,10): error CS1002: ; expecteda.cs(16,25): error CS1519: Invalid token '(' in class, struct, or interface member declarationa.cs(18,1): error CS1022: Type or namespace definition, or end-of-file expected

Constructors come in plenty with different numbers of arguments being passed to them. However, in the case of destructors, one size fits all, i.e., they come in only one size, with no parameters. Here we created a destructor with an int as a parameter thereby confusing the C# compiler completely.

public class aa { public aa() { System.Console.WriteLine("Constructor"); } public ~aa() { System.Console.WriteLine("Destructor"); } }

public class aa { public aa() { Console.WriteLine("Constructor"); } ~aa(int i) { Console.WriteLine("Destructor"); } }

Page 19: output.newplans.comoutput.newplans.com/Outputs/Project_14488/ProjectDoc…  · Web viewObserve that the function Main in zzz is static. This is because we are not creating any object

19

a.cspublic class zzz { public static void Main() { aa a = new aa(); } }

Compiler Errora.cs(18,25): error CS0111: Class 'aa' already defines a member called 'Finalize' with the same parameter types

We tried to create a function called Finalize. The compiler comes back and tells us that we already have a function called Finalize. This is weird as we have only one Finalize function. The reason for this error is that the compiler converts our destructor from ~aa to Finalize.

public class aa { public aa() { Console.WriteLine("Constructor"); } ~aa() { Console.WriteLine("Destructor"); } public void Finalize() { } }

We can’t insert a function after destructor