Click to See Complete Forum and Search --> : About abstract/sealed/virtual/override/new keywords...


bhushan1980
May 22nd, 2008, 04:10 PM
Hi all. I have following simple questions:

<1> What is the difference between abstract class and an interface?
I know the following-
- Fields/member vaiables are allowed in abstract class, where as they are not allowed in an interface.
- The class implementing an interface has to implement all the methods/properties/delegates in the interface, but a class inheriting an abstract class need not implement all the methods/properties/delegates in the base class which is abstract class. But I am not sure if the user has to simply ignore the methods or he has to declare them as abstract in the derived class if he is not going to implement that method?
- No constructors, destructors, garbage collection in an interface. Please comment on this one...

<2> In an enterprise development, which one comes first - an abstract class or an interface? This was an interview question.

<3> What is happens when the keyword abstract is used to declare and implement a method? What happens when a keyword sealed is applied to a method?

<4> Can we have virtual/override/new keywords attached to a contructor in C#? If yes, then answer the following:

class A
{
public virtual A(){ }
}

class B : A
{
public override B(){ }
}

class C : B
{
--------------- C(){ } // Mention the keyword(s) that will come here
// if the base class c'tor is to be invoked and otherwise
}


<5> What is the analogous of C# static keyword in VB.NET?

<6> Is there a C# equivalent for keywords My, AddressOf, With in C#? If not then how are the tasks done by them in VB.NET performed in C#?

<7> Which of the ways is cost effective? Boxing or Unboxing?

Although I have a rough idea of all the Qs, I am not 100% confident about them. So please give all your inputs...

Thankyou,
Bhushan.

Shuja Ali
May 22nd, 2008, 04:27 PM
Let us do it like this. You tell us what answers you have for the questions and then we will give inputs. I guess that way we will come to know about your understanding of all the questions and then clear any misunderstandings.

bhushan1980
May 22nd, 2008, 05:13 PM
Hi all. I have following simple questions:


<1> What is the difference between abstract class and an interface?
I know the following-
- Fields/member vaiables are allowed in abstract class, where as they are not allowed in an interface.
- The class implementing an interface has to implement all the methods/properties/delegates in the interface, but a class inheriting an abstract class need not implement all the methods/properties/delegates in the base class which is abstract class. But I am not sure if the user has to simply ignore the methods or he has to declare them as abstract in the derived class if he is not going to implement that method?
- No constructors, destructors, garbage collection in an interface.
-----------------------------------------------------------------------------------------------
"Please comment on this one..."{;;}


<2> In an enterprise development, which one comes first - an abstract class or an interface? This was an interview question.
------------------------------------------------------------------------------------------------
"I think that it is the interface first because of the simple fact that the abstract classes can derive from the interfaces and then can implement the interface and all the successive classes might be derived from the abstract class, which gives us the option of including/excluding the methods/properties/delegates/indexers declared in the interface. Also, we can add some fields in the derived abstract class to add functionality it implements. In addition to it, the coder can customize the base functionality provided by the interface for an abstract class."

<3> What is happens when the keyword abstract is used to declare and implement a method? What happens when a keyword sealed is applied to a method?
----------------------------------------------------------------------------------------------
"I am not sure about this. But simply put, an abstract method does not have an implementation. But, if any class, even if it has a single abstract method, has to be declared as abstract. I do not know the purpose of declaring a method abstract in real time applications. If a method is declared as sealed, then it cannot be overridden or newed. I am not sure about this as well.

<4> Can we have virtual/override/new keywords attached to a contructor in C#? If yes, then answer the following:



class A
{
public virtual A(){ }
}

class B : A
{
public override B(){ }
}

class C : B
{
--------------- C(){ } // Mention the keyword(s) that will come here
// if the base class c'tor is to be invoked and otherwise
}

----------------------------------------------------------------------------------------------
The blank will be public override if a base class constructor has to be invoked and it would be public/private/protected + new if it does not want to invoke the base classes. I need more information on this.

<5> What is the analogous of C# static keyword in VB.NET?
-----------------------------------------------------------------------------------------------
"Shared". However, I asked this because VB.NET has a keyword Static which is used in some other context and I want to know what is that context?

<6> Is there a C# equivalent for keywords My, AddressOf, With in C#? If not then how are the tasks done by them in VB.NET performed in C#?
-----------------------------------------------------------------------------------------------
I do not know about the equivalent keywords. I just know that the things are done a little differently in C#.

<7> Which of the ways is cost effective? Boxing or Unboxing?
-----------------------------------------------------------------------------------------------
I do not know for sure, but boxing causes the casting of the other/simple datatypes such as int/float/double to object types which is inturn involved with the conversion of value types to reference types. Unboxing is reverse of boxing. So, if simple data types are converted to object types there has to be a specific and valid reason for doing so. For instance, if someone has to use the methods of Object class. Otherwise, boxing is not help ful as it only adds to list of operations. And hence it is costly.
Please comment....

Although I have a rough idea of all the Qs, I am not 100% confident about them. So please give all your inputs...

Thankyou,
Bhushan.

Thread1
May 22nd, 2008, 09:00 PM
Why not check your VS documentation or visit the MSDN? ;)

boudino
May 23rd, 2008, 02:00 AM
I'll answer only the most interesting and not trivial question:
<1> What is the difference between abstract class and an interface?

The main difference is that interface respresents loose coupling, while abstract class represents tight coupling.

Other significant difference is that interface declares a contract, while abstract class implies implementation.

Please take this a suggestion to your study (sorry, but your are touching trivia, which cannot be explained in few words).

bhushan1980
May 23rd, 2008, 10:54 AM
Hi.
Thank you for all the replies. Shuja asked me to mention the things that I know, so I did explain them. Regarding going through Visual Studio documentation, I have gone through it all the time and will continue to do so. I can get all the problems solved there, except a few. Not out of any sort of complacency, I just missed the entire plot to explain myself clearly. What I am looking for here, are the things that are not easily found/understood in the documentation. And I am terribly sorry about that. The questions that I have asked are just to engage into some discussions and I believe that through discussions we come to know a few things that we might have skipped. For instance, the point mentioned by boudino is a good one although I have not looked it up and try to find more on it to discuss. I had once read about COM interop and RCW (Runtime Callable Wrapper) and in that I came across early and late binding of the COM interfaces. But these terms i.e., 'loosely coupled' and 'tightly coupled' are new to me. I will into them for sure. Also, when boudino says that "an interface is a contract and an abstract class implies implementation" do you mean that in a software development world, interfaces are developed according to the strategic software plan where as abstract classes are more of customization and extensions of an interface or they can even be on their own without being derived from an interface.
So, in the end, I urge u all to give me the out of box information that is not easily available on MSDN. Whereever, the entire question or topic does not have anything other than trivial, please type a single word 'TRIVIAL' and I will accept it. I would be more than happy if a member is able respond to (or address) a small part of my queries.

Thanks and Regards,
Bhushan.

P.S.: I am still looking for brief discussions on some of the questions; more importantly <2>, <4>, <6>, <7>.

TheCPUWizard
May 23rd, 2008, 01:43 PM
I'll answer only the most interesting and not trivial question:


The main difference is that interface respresents loose coupling, while abstract class represents tight coupling.

Other significant difference is that interface declares a contract, while abstract class implies implementation.

Please take this a suggestion to your study (sorry, but your are touching trivia, which cannot be explained in few words).

Of course that misses the BIGGEST difference. C# alows derivation from only a single class, but from multiple interfaces. So if you create two abstract classes, you can NOT derive a class that implements BOTH of them. However if you have developed two interfaces......

bhushan1980
May 23rd, 2008, 03:07 PM
Ahhh! How did we miss that! I knew it as one of the basic differences between the two; yet due to my extra-ordinary talent to forget the most easiest things to remember, I could achieve these levels of incompetence! Again, HAIL THECPUWIZARD!
One Q pops out of my mind though is, why at all do we need nested interfaces?

Regards,
Bhushan.

Mutant_Fruit
May 23rd, 2008, 07:14 PM
One Q pops out of my mind though is, why at all do we need nested interfaces?
Assuming you mean 'why do we want an interface to inherit from an interface', i think this shows why it's good:


public interface IEnumerable
{

}

public interface IList : IEnumerable
{

}


A collection can be represented at it's most basic form as a bunch of objects which you can iterate over. This is the 'IEnumerable' interface. This is a contract. It guarantees that you can iterate over these elements.

An IList is another contract. It allows you to access the elements by index, remove elements, add elements etc. In a list, you want to be able to iterate over the elements aswell, so IList will inherit from IEnumerable.

Does that make sense?

TheCPUWizard
May 23rd, 2008, 07:49 PM
A nested interface is actually:


interface INest
{
interface IBird
{
void Fly()
}
void Something(IBird bird);
}


Like any other nested construct it is because the inner (IBird) is intended to have meaning only within the context of the outter (INest).

The exact same question would apply to nested classes, or even namespaces themselves... And if you are asking that question...it is time to go back to the basics....

bhushan1980
May 24th, 2008, 11:19 AM
I am switching (or rather thrown) back and forth into professional world and the so called basics world. Writing a nested class can be as simple as a breeze. But, things climax when we start adding some references and contexts. For instance, as you mentioned, if we can nest an interface inside another, an abstract class being analogous to an interface, can an abstract class be declared and implemented inside an abstract class? If yes, then how can we access the inner abstract class and its members in the derived class?

public abstract class Outer
{
public String str1;
public abstract void OuterMethod1();
public abstract int OuterMethod2(int X);

public abstract class Inner
{
public String str2;
public abstract void InnerMethod1();
public abstract int InnerMethod2();
}

public String OuterProperty{ get; set; }

}

class Extend : Outer
{
......
......
......
// How do you access the nested abstract class members?
// Or is it that just as any nested class, it is created for use within
// the scope of the outer class? The derived classes need not access it?
}



I understand that, in these lines, I have entered more into trivia. But believe me, there are some questions that are really coming up ahead.

Thankyou,
Bhushan.

Arjay
May 24th, 2008, 12:32 PM
For instance, as you mentioned, if we can nest an interface inside another, an abstract class being analogous to an interface, can an abstract class be declared and implemented inside an abstract class? If yes, then how can we access the inner abstract class and its members in the derived class?How would either one be useful?

bhushan1980
May 24th, 2008, 02:10 PM
I do not know Arjay...That is what I am into. Is there or can there be a situation or need where you have to use either of the 2 i.e., a nested abstract class inside an abstract class and an interface inside an interface? I know about the latter one now... as it was explained by TheCPUWizard. Also, I knew about the regular nested classes. But how about the nested abstract classes? I am asking this because, while working with C++, I never came across a need where you have to create nested classes. We can always the create the instances of the classes created outside the class whereever appropriate and desired. The concept of nested class came to me while with C# which has adopted or has tried to adopt majority of OOPs benefits and strengths provided by C/C++ and Java. Here is an MSDN link that explains about nested classes in C++:
http://msdn.microsoft.com/en-us/library/x23h0937(VS.80).aspx
Another good link for C++ is found on IBM website and that is:
http://publib.boulder.ibm.com/infocenter/lnxpcomp/v8v101/index.jsp?topic=/com.ibm.xlcpp8l.doc/language/ref/cplr061.htm
Another one showing the comparison of nested classes in C# and Java:
http://blogs.msdn.com/oldnewthing/archive/2006/08/01/685248.aspx
Hey Arjay check out this one an interesting one:
http://staff.develop.com/jasonw/weblog/2003/02/05.html#a151
I still have to complete come to the terms as to how the implementation has worked for the writer...

Again, sorry to bring in C++ into C# forums, but all these things might apply to C# as well, except a few such as including the use of typedefs and pointers in C++ to achieve certain functionality.

Thanks,
Bhushan.

TheCPUWizard
May 24th, 2008, 09:15 PM
1) An abstract class is completely different than an interface. (although they are effectively the same in C++, this IS the C# forum).

2) You NEVER need a nested class (abstract or otherwise) nor a nested interface. They are simply constructs that provide "intent".

riscutiavlad
May 25th, 2008, 02:02 AM
Hi all. I have following simple questions:

<1> What is the difference between abstract class and an interface?
I know the following-
- Fields/member vaiables are allowed in abstract class, where as they are not allowed in an interface.
- The class implementing an interface has to implement all the methods/properties/delegates in the interface, but a class inheriting an abstract class need not implement all the methods/properties/delegates in the base class which is abstract class. But I am not sure if the user has to simply ignore the methods or he has to declare them as abstract in the derived class if he is not going to implement that method?
- No constructors, destructors, garbage collection in an interface. Please comment on this one...

<2> In an enterprise development, which one comes first - an abstract class or an interface? This was an interview question.

<3> What is happens when the keyword abstract is used to declare and implement a method? What happens when a keyword sealed is applied to a method?

<4> Can we have virtual/override/new keywords attached to a contructor in C#? If yes, then answer the following:

class A
{
public virtual A(){ }
}

class B : A
{
public override B(){ }
}

class C : B
{
--------------- C(){ } // Mention the keyword(s) that will come here
// if the base class c'tor is to be invoked and otherwise
}


<5> What is the analogous of C# static keyword in VB.NET?

<6> Is there a C# equivalent for keywords My, AddressOf, With in C#? If not then how are the tasks done by them in VB.NET performed in C#?

<7> Which of the ways is cost effective? Boxing or Unboxing?

Although I have a rough idea of all the Qs, I am not 100% confident about them. So please give all your inputs...

Thankyou,
Bhushan.

<1> Lots of good anwsers above.

<2> It depends on the actual needs. If you need members and abstract methods, use an abstract class. If you need a contract use an interface. There is no rule to which one comes first - that's why they both exist. Maybe the expected anwser was to first declare interfaces then declare abstract classes that implement those interfaces but again, it all depends on the design.

<3> If you declare a method as abstract, you cannot implement it. You can implement it only on a derived class.
You can use the word sealed on a method declaration when you implement a method declared with the override keywords so that classes that derive from the class where you implemented it (with the sealed keyword) won't be able to override it again - they will be forced to use the sealed implementation.

<4> Those keywords are illegal for constructors. Constructors, by definition, initialize requiered members of a class. When instantiating a derived class, the constructor of the parent class is called implicitly to make sure everything is initialized the way it should - that's why it doesn't make sense to be able to override constructors.

<5><6> Sorry, no VB.NET experience

<7> Boxing and unboxing go hand in hand. Boxing means putting a value type on the heap instead of the stack by treating it like a reference type, unboxing means taking a boxed value and putting it back on the stack. The cost effective way is not using boxing and unboxing.

JonnyPoet
May 25th, 2008, 08:24 AM
<2> In an enterprise development, which one comes first - an abstract class or an interface? This was an interview question...
Thats IMHO a question pointing to design pattern rules. And here we have clearly said that using compositions is prefered before inheritance. This would lead to the following decision: If you can choose to use an abstract class or an interface to implement a specific requirement then choose the interface implementation.

boudino
May 26th, 2008, 01:45 AM
You are right, I've forgotten it. Maybe because I strongly reject to use inheritance as main design approach. I prefer interfaces and composition, so I very rarely come accross the lack of the limitation of inheritance to just one predecestor

bhushan1980
June 1st, 2008, 05:03 PM
Hi. One more addition here. I searched on google and I came to know that we can have an implementation of a function inside an abstract class as well! So first of all let me know if this is true? And if it is, then please tell me how can we call or interact with that function?

Thankyou,
Bhushan.

TheCPUWizard
June 1st, 2008, 05:07 PM
Hi. One more addition here. I searched on google and I came to know that we can have an implementation of a function inside an abstract class as well! So first of all let me know if this is true? And if it is, then please tell me how can we call or interact with that function?

Sure. An Abstract Class must have at least one Abstract Method, it can have zero or more "Concrete" methods (ie It does not have to be "Pure"). This is the advantage of an Abstract class over an interface.

IF an abstracxt class had to be pure, then it would only have the capabilities of an interface, but with additional restrictions....now very useful... :rolleyes:

bhushan1980
June 1st, 2008, 06:11 PM
Suppose I am implementing an interface in the .NET framework directly and not inheriting from the implementing class in the .NET framework, then as per the rule, do I have to provide an implementation for all the methods? Say for instance:

// If I am implementing an interface for text-box as
public class MyTextBox : ITextEditor
{
.....
}

An interace like ITextEditor has a lot of methods and properties. So am I supposed to implement all of them?

Thankyou,
Bhushan.

TheCPUWizard
June 1st, 2008, 06:42 PM
edit: Me Bad..See Reply #23.... :blush: :blush:

EVERY concrete class MUST provide an implementation of EVERY method and property, either explicitly or in one of it's base CLASSes.

JonnyPoet
June 1st, 2008, 06:55 PM
...class as well! So first of all let me know if this is true? And if it is, then please tell me how can we call or interact with that function?
Simple try it. You will see that you can use it the same way as you are using methods of an inherited class. Here is an example
using System;
using System.Collections.Generic;
using System.Text;
namespace DesignPatternsChapOne {
// Strategiepattern
public interface IWeaponBehaviour {
void UsedWeapon();
}
public abstract class Hero {
public IWeaponBehaviour _weapon;
public void Fight() {
_weapon.UsedWeapon();
}
public void SetWeapon(IWeaponBehaviour wp) {
_weapon = wp;
}
}
// and here the implementations
public class Messer :IWeaponBehaviour {
#region IWeaponBehaviour Member
public void UsedWeapon() {
Console.WriteLine("This is a knife for cutting and stick someone.");
}
#endregion
}
public class BowAndArrow : IWeaponBehaviour {
#region IWeaponBehaviour Member
public void UsedWeapon() {
Console.WriteLine("The arrow goes directly to the heart. ( If you dont miss the target )");
}
#endregion
}
public class Axe : IWeaponBehaviour {
#region IWeaponBehaviour Member
public void UsedWeapon() {
Console.WriteLine("This is a very heavy thing to hit. Orks are using that.");
}
#endregion
}
public class Sword : IWeaponBehaviour {
#region IWeaponBehaviour Member
public void UsedWeapon() {
Console.WriteLine("To use a sword is a special art.");
}
#endregion
}
public class Szepter : IWeaponBehaviour {
#region IWaffenverhalten Member
public void UsedWeapon() {
Console.WriteLine("If it is heavy enough you may kill the person by a hit of its weight.");
}
#endregion
}
// und die Figuren
public class King : Hero {
public King() {
_weapon = new Szepter();
}
}
public class Queen : Hero {
public Queen() {
_weapon = new BowAndArrow();
}
}
public class Troll : Hero {
public Troll() {
_weapon = new Axe();
}
}
public class Knight : Hero {
public Knight() {
_weapon = new Sword();
}
}
}


And you can call this in any method like this
King myKing = new King();
myKing.Fight();
myKing.SetWeapon(new Messer());
myKing.Fight();
You will see the king changes his weapon. This is a very useful pattern. Your interface may contain 20 methods. You implement them in a seperated class.like we have a knife class, a sword class... you may have lots of such classes each contains the same methods and properties but each for a different purpose.
You have a method in your abstract class calling the methods of your interface. So here an abstract class work together with an interface :D
Very funny, very clever :lol: :lol: ;)

boudino
June 2nd, 2008, 01:48 AM
Sure. An Abstract Class must have at least one Abstract Method, it can have zero or more "Concrete" methods
Maybe in C++, but in C#, it definitely has not.

JonnyPoet
June 2nd, 2008, 06:59 AM
Maybe in C++, but in C#, it definitely has not.You are right boudino, look at my workable example in post #22 it has no abstract method in the abstract class.

TheCPUWizard
June 2nd, 2008, 07:14 AM
Maybe in C++, but in C#, it definitely has not.


Please Reread Post #21.... :D

(Thanks) :wave: :wave:

cjard
June 2nd, 2008, 04:23 PM
bhushan1980 == (George2 with humanity upgrade 1.0 installed)? :eek: :ehh: :D

Re the abstraction argument; indeed.. abstract merely requires that a subclass either provide an implementation of that wich is abstract, or defer implementation to antoher subclass

i.e. marking a class as abstract prevents it from being instantiated directly. A subclass must be created
Marking a method as abstract naturally causes the class to become abstract, because the method is not implemented, the class does not represent a complete workable block of code and hence cannot be created.

It thus follows that a class can be abstract (forcing the developer to subclass it in order to instance it) even if none of its members are abstract.

I do think the compiler error "Class XYZ must be marked abstract: it does not implement ABC" is quite succinct at explaining all this, but maybe thats just me

cjard
June 2nd, 2008, 04:27 PM
You are right, I've forgotten it. Maybe because I strongly reject to use inheritance as main design approach. I prefer interfaces and composition, so I very rarely come accross the lack of the limitation of inheritance to just one predecestor

Interesting comment, given that every class you use while youre coding, is way down an inheritance hierarchy already.. ;)

cjard
June 2nd, 2008, 05:21 PM
What is the difference between abstract class and an interface?
abstract classes can have some ability to function (because they can contain implementatin code), interfaces have no functional code at all. they mostly define what comes in and what goes out so the compiler can do some compile time type checking ;) and other developers know what kind of data to pass around

In an enterprise development, which one comes first - an abstract class or an interface?
This question doesnt make sense to me.. It's like asking what comes first, a shopping list (interface - defines what goes in and out, doesnt impl) or a box of ready-made cake mix (abstraction of a cake - just add milk). I never needed one before the other.

What is happens when the keyword abstract is used to declare and implement a method?
Nonsense question: You cant implement a method that is marked abstract

What happens when a keyword sealed is applied to a method?
You cannot override that method witha new implementation in a subclass


Can we have virtual/override/new keywords attached to a contructor in C#?
Constructors dont really partake in all the usual inheritance shenanigans. They behave like they are new, which is why you must explicitly state base(args) when you want to call the parent cosntructor. You should be aware that if you do not provide a constructor, C# provides a default one (literally inserts it into your code when compiling) that takes no args and calls the base() again with no args. If no base constructor takes no args then you must provide a constructor to get around this behaviour because the error indicating the base class has no matching constructor, is seen.
This is not constructor inheritance..

What is the analogous of C# static keyword in VB.NET?
shared. vb.net's static is for method variables that retain their value between calls, a somewhat dumb and clumsy idea that c# ditched. if you need the functionality, use a class level variable instead; it's how the vb.net compiler fudges it behind the scenes


Is there a C# equivalent for keywords My, AddressOf, With in C#?

this, (not needed; methods can be treated like objects when dealing with delegates), using

read this: http://www.harding.edu/fmccown/vbnet_csharp_comparison.html


here's attaching an eventhandler in c#:
obj.Event += Handler(methodName)

vb:
AddHandler obj.Event, AddressOf methodName



Which of the ways is cost effective? Boxing or Unboxing?

neither

Arjay
June 2nd, 2008, 05:31 PM
a box of ready-made cake mix (abstraction of a cake - just add milk).I always like the cake mix that comes with frosting. I'm not sure if it's IFrosting or FrostingBase, but it's good.

cjard
June 3rd, 2008, 04:53 AM
/me munches on a bowl of Reduced Sugar Kelloggs Frosties (http://farm1.static.flickr.com/8/7971853_833009d69e.jpg?v=0)* and wonders the same thing


*the concept of which i find one of the most amusingly pointless in the breakfast cereal world.. Frosties = cornflakes + sugar, so if you want frosties without sugar.. ;)

bhushan1980
June 3rd, 2008, 06:22 PM
Hi...It seems that there are a lot of things happening here...Our forums-mate cjard has got quite handsome 'blogging' skills and I do really appreciate them. Also, it seems that cjard has a deep interest in blogging. May be I am a little too young in the field of IT development and a little too immature to understand the versatility of a power-poster like the one and only "cjard". But, I would like "cjard" to be a little "verbose"(and not very discrete)


bhushan1980 == (George2 with humanity upgrade 1.0 installed)?


Regarding the above quote:
I like the way it is build/represented...The presentation layer seems ok. But regarding the business logic, I have following Qs:
<1> What is the use of the Quote class provided above? Can I create an instance of it and understand how it would be of any help to me?
<2> Is there anything encapsulated/abstracted that I need to know? (Because if it was intended for me to know, and if that was abstracted, that is a wrong according to the OOPs paradigm. And further more complete encapsulation does not help either.) So, I urge you to explain the meaning of the Quote.
<3> If it is supposed to be shipped as a DLL, please provide relevant documentation.
<4> Atleast send me some really good string parsers that give the hidden meaning of the idioms/phrases that are way out of league of any famed literary person.

=====================================================
JOKES AND QUOTES apart...


In an enterprise development, which one comes first - an abstract class or an interface?

This made sense to the interviewer! May be he just wanted to test the person whom he was interviewing. Although, I had a faint idea about the either being preceding the other one, I had to ask some of the other people and I am happy to say that I was right on this one.


What is happens when the keyword abstract is used to declare and implement a method?

I admit that this was the non-sense question not because of the fact that the Q was non-sense, but the effort I put in answering what I knew about it in my second post, just held myself back a little bit. So sorry about it.


Can we have virtual/override/new keywords attached to a contructor in C#?

Again its the interviewer's stupidity. Cannot do anything about it. Yet it is always good to know. I would have normally said that the code would not compile.


What is the analogous of C# static keyword in VB.NET?
Is there a C# equivalent for keywords My, AddressOf, With in C#?

Answers to both the questions are really good. And I really appreciate them. I had not got them so far....

Thankyou and Regards,
Bhushan.

TheCPUWizard
June 3rd, 2008, 06:55 PM
Bhushan,

Be careful before you consider an interviewer "stupid", although there are plent of them.

I will often ask "stupid" question to see how the candidate reacts...

Either that or I will ask questions which typically illicit "boiler plate" responses which are wrong....

1) What does the Dispose() method of a class do???

2) When is Dispose() called by the Runtime?

More than half of all candidates get either or both of these WRONG....

I don't know if the expression "Crazy Like a Fox" translates well into your native tongue, but it should be a "fun" one for you to research... :wave: :wave:

bhushan1980
June 4th, 2008, 10:38 AM
Hi.
The two questions that TheCPUWizard has put here, have to have some concrete and distinct way of answering them. I have come across a numerous answers that seems to be right, but you never know if they are 100%. Here is what I know:

=====================================================

1) What does the Dispose() method of a class do???

It invokes the destructor/finalize method explicitly. There are certain situations when you might require to start the garbage collection explicitly. The dispose() method makes calls to the destructors or finalize() method. I do not know if framework calls Dispose() method implicitly? The very first time I saw a question about destructors in C#, I was surprised because I never knew about them. Then on, I understood that the destructors very much exist in C#, but they are controlled by Garbage Collectors unlike C++. So, all these things happening behind the scenes, what should be the simple answer to the above question that would best appease an interviewer?
Here is a link I found some good information on C# destructors:

http://www.c-sharpcorner.com/UploadFile/chandrahundigam/UnderstandingDestructors11192005021208AM/UnderstandingDestructors.aspx

Another random link tells us the following:

http://www.ondotnet.com/pub/a/dotnet/2002/02/11/csharp_traps.html

In C#, however, this syntax is simply a shortcut for declaring a Finalize() method that chains up to its base class. Thus, when you write:

~MyClass()
{
// do work here
}

the C# compiler translates it to:

protected override void Finalize()
{
try
{
// do work here
}
finally
{
base.Finalize();
}
}

=====================================================


2) When is Dispose() called by the Runtime?

Normally Dispose() is called at the runtime by garbage collector. Initially, I read in a lot of places that the garbage collector frees the allocated memory in a random fashion. But later on as I came to know that it is called when, the system is running low on resources and GC has to free some of them. Further, as I read, I understood that the objects were freed in the reverse manner they were created. That means the objects that have been alive for a longer time took more efforts for GC in deleting than the ones that were recently created. I am not sure why this is true and how? Also, Dispose() can be explicitly called by the developer in certain situations as discussed in first Q.
=====================================================

Thankyou and Regards,
Bhushan.

Mutant_Fruit
June 4th, 2008, 10:44 AM
It invokes the destructor/finalize method explicitly.
Nope. The finalizer will only ever be called in the finalizer thread when the object is ready to be freed by the GC. The runtime will never call the Dispose method automatically.

Dispose is a user created, user callable method which is typically used to immediately release unmanaged resources as opposed to waiting for the GC to free the object.

Typically the finalizer is used to ensure that dispose is called, so the finalizer will typically call the dispose method. MSDN has good information on the finalize/dispose pattern.