OOPS CLASS

A class is a programming language construct used to group related fields and method. It describes the rules by which objects behave; these objects are referred to as instances of that class. A class specifies the structure of data (like properties, fields, attributes, data members) within each instance as well as methods which manipulate the data of the object and perform tasks. A class is the most specific type of an object in relation to a specific layer. Fields are variables in a class. By default, a class is a private. Class is the root word of classification. When you design a class, you systematically arrange information into a meaningful entity. This arranging is an act of classification. In C#, you use the class keyword, a name, and a pair of curly braces to define a new class. The data and methods of the class occur in the body of the class, between the curly braces. Example: class Circle { double Area() { return 3.141592 * radius * radius; } double radius; } A class is a definition of type.

OBJECT
An object is the individual run-time unit that is used as the basic building block of programs. An object is an instantiation (instance) of a class. A class is only a blueprint offering a defined functionality. That functionality is actually implemented by creating an instance of that class, in form of an object. To use the functionality of a particular class, an object of that class must be created first. An object is an instance of class type, created when the program runs. Example: Circle c; //create a circle variable c = new Circle(); //initialize it

The new keyword instantiates a class and an object is created of type Circle whose reference is stored in c.

CONSTRUCTOR
When a ‘new’ keyword is used to create an object, the CLR has to construct an object by using the definition of the class. The CLR has to grab a piece of memory from the operating system, fill it with the fields defined by the class, and then call the constructor to perform any initialization required. A constructor is a special method; it has a same name as the class, it can take parameters, but it cannot return a value (not even a void). Every class must have a constructor. If u don’t write one, the compiler automatically generates one. The default constructor is a constructor that doesn’t take any parameters. It does not matter whether the compiler generates it or u write it, it is still the default constructor. A non-default constructor is like a default constructor but it can be overloaded (can have parameters). Example: class Circle { public Circle() // default constructor { radius = 0.0; } public Circle(double initialRadius) // overloaded constructor { radius = initialRadius; } public double Area() { return 3.141593 * radius * radius; } private double radius; } If the constructor is private, it cannot be used outside a class, which will prevent u from creating an object from methods that outside a class. If you write your own constructor for a class, the compiler does not generate a default constructor. Therefore, if you’ve written your own constructor that accepts one or more constructor that accepts one or more parameters and you also want a default constructor, you’ll have to write the default constructor.

Once again. you have no control over this phase. Second.The new operation is atomic.instanceCount. it has to initialize the object. } . private static int instanceCount = 0. First. Restrictions on destructors: 1) Cannot declare a destructor in a struct coz struct is a value type. You can use a destructor to perform any tidying up required when an object is garbage collected. You can control this phase this by using a constructor. the new operation has to convert the raw memory into an object. DESTRUCTOR Like object creation. Its main purpose is to clean up and to free the resources which were acquired by the object along its life cycle and unlink it from other objects or resources invalidating any references in the process.instanceCount++. the raw memory has to be given back to the heap. } public static int InstanceCount() { return this. The syntax for writing a destructor is a tilde (~) followed by the name of the class. object creation is really a two-phase process. . but underneath. the new operation has to allocate some raw memory from the heap. object destruction is also a two-phase process. You have no control over this phase of an object's creation. Second. First. you have to perform some tidying up. The two phases of destruction exactly mirror the two phases of creation. the memory that the object lived in has to be reallocated. } ~Tally() { this..instanceCount--. } A destructor is a method which is automatically invoked when the object is destroyed. You do this by writing a destructor.. Example: class Tally { public Tally() { this.

It is the most permissive access level. This ensures that a destructor always calls its base class destructor. If no access modifier is specified then by default the compiler considers it has private. and from within any class derived from the class that declared this member.Finalize method. Internal members are accessible only within files in the same assembly. 4) Internal: The internal keyword is an access modifier for types and type members. It has the least permissive access level. The private members are only accessible in the same class.2) Cannot declare access modifier coz u can never call a destructor-the garbage collector does. A protected of a base class is accessible in a derived class only on derived class reference i. 3) Protected: The protected keyword is a member access modifier.e. can only have internal or public accessibility. 2) Private: The private keyword is a member access modifier. followed by a finally block that calls the base class Finalize. ACCESS MODIFIER Access modifiers are keywords used to specify the declared accessibility of a member or a type. Namespaces have no access restrictions. 4) The compiler automatically translates a destructor into an override of Object. which are not nested into other types. A struct cannot be protected coz it does not support inheritance. Access modifiers are not allowed on namespaces. The compiler generated Finalize method contains the destructor body inside a try block. It is used only for classes. The public members have no restriction in accessing. There are five types of access modifiers in C#: 1) Public: The public keyword is an access modifier for types and type members. U can’t override Finalize nor call it. 5) Protected Internal: The members are accessible in the derived class of the base class and also by the other classes of the same assembly. Top-level types. 3) Destructor cannot have parameters coz u cannot call it. . The default accessibility for these types is internal. through derived class type. A protected member is accessible from within the class in which it is declared.

The default for an enum and interface is public. making the fields of a structure public is not advisable in most cases. a member can be referenced. the memory management overhead is often reduced (as long as the structure is reasonably small). Use structs for lightweight concepts where it makes sense to copy the value. } As with classes. The accessibility domain of a member specifies where. its accessibility domain is determined by both the accessibility of the member and the accessibility domain of the immediately containing type. or null—just like for a class. If the member is nested within another type. In a class. A structure can have its own fields. seconds. and constructors just like a class (and unlike an enumeration). 1) You can't declare a default constructor (a constructor with no parameters) for a struct. By default. In C#. A better idea is to make the fields private and provide your structure with constructors and methods. long and float are structures. The reason you can't declare your own default constructor in a struct is because the compiler always generates one. the primitive numeric types int. methods. and use classes for more heavyweight concepts where it doesn't make sense to copy the value. you use the struct keyword followed by the name of the type. the class can contain so little data that the overhead of managing the heap becomes disproportionate. false. Therefore.The default for a class and struct is private. in the program sections. there is no way to ensure that public fields contain valid values. structure is private. Because structures are stored on the stack. Difference between class and struct: A structure and a class are syntactically very similar but there are a few important differences. STRUCTURES In some cases. minutes. you should . In these cases it is better to define the type as a structure. The compiler-generated default constructor for a structure always sets the fields to 0. but it is a value type and not a reference type. the compiler generates the default constructor only if you don't write a constructor yourself. Example: struct Time { public int hours. To declare your own structure value type. followed by the body of the structure between opening and closing braces.

take over (or inherit) attributes and behavior of the pre-existing classes. The new classes. In case of a class. a constructor should be called to initialize the variable. at most. By default. It is intended to help reuse existing code with little or no modification. When you copy a struct variable. a class is not allowed to derive from two or more classes.ensure that a structure value created by the default constructor behaves logically and makes sense with these default values. Also u cannot initialize or assign one struct variable to another without initializing the variable that has to be copied or assigned. Any initialization should be done from the non-default constructor.. the compiler won't initialize it for you. you cannot. } A derived class automatically contains all fields from the base class. These fields require initialization when an object is created. INHERITANCE (MULTIPLE) Inheritance is a way to form new classes using classes that have already been defined. if you don't initialize a field in the constructor. which are referred to as base classes (ancestor). known as derived classes. you can create further derived classes that inherit from DerivedClass using the same syntax: class DerivedSubClass : DerivedClass { . However. } The derived class inherits from the base class. unless DerivedClass is declared as sealed. This copying is done as a fast single-block copy that never throws an exception. 2) In a class. In a struct. The syntax for declaring that a class inherits from another class is as follows: class DerivedClass : BaseClass { . . However.. In C# a class is allowed to derive from. if you’ve to make a copy of a variable then both the variables refer to the same object. you can initialize fields to different values by providing a non-default constructor. the constructor for a derived class must call the constructor for its base class.. inheritance is public and it only allows public access. U cannot use a struct type variable after it is declared. If you don't want to use these default values.e. This means you must explicitly initialize all the fields in all the structure constructors or you'll get a compile-time error.. you can initialize instance fields at their point of declaration. 3) Structure does not support inheritance. It has to be initialized with a ‘new’ keyword i. Therefore. one other class. each field on the left side is copied directly from its corresponding field on the right side.

Even though. Only subclass reference will allow access to all methods of its class. you can silence the warning by using the new keyword as follows: class Token { . However. } If you don't explicitly call a base class constructor in a derived class constructor. if you're sure that you want the two methods to have the same signature. a super class can refer to its subclass object but subclass cannot refer a super class object.. It is possible to refer to an object from a variable of a different type as long as the type used is a class that is higher up the inheritance hierarchy i.. you will receive a warning when you compile the application. However. the compiler attempts to silently insert a call to the base class's default constructor. } } class IdentifierToken : Token { . but does not know which one to use.Example: class IdentifierToken : Token { public IdentifierToken(string name) : base(name) // calls Token(name) { . not all classes have a public default constructor. VIRTUAL If a base class and a derived class happen to declare two methods that have the same signature (the method signature is the name of the method and the number and types of its parameters). This works because System.e.Object has a public default constructor. because the compiler must insert a call to a constructor. By default the super class methods are accessed when they are referred. } .. } } .. in which case forgetting to call the base class constructor results in a compile-time error.. It can only look into those methods which are common to both super and subclasses.. new public string Name() { ..... public string Name() { .. The method in the derived class masks (or hides) the method in the base class that has the same signature. a super class can refer a subclass object it cannot look into all the subclass methods..

Using the new keyword like this does not change the fact that the two methods are completely unrelated and that hiding still occurs.. You can mark a method as a virtual method by using the virtual keyword. } . you can use the protected keyword to tag members. A method that is intended to be overridden is called a virtual method. a derived class can use the override keyword to declare another implementation of that method. In this situation. while hiding these same members from classes that are not part of the hierarchy.. OVERRIDDING Overriding a method is a mechanism for providing different implementations of the same method—the methods are all related because they are intended to perform the same task. If a base class declares that a method is virtual.. based on the type of the object determined dynamically by the runtime. a virtual keyword is used where the subclass method will override the super class method for future extensions... hiding a method is probably an error. Example: class IdentifierToken : Token { . . It just turns the warning off. To avoid this. it is useful for a base class to allow derived classes to access some of its members.. A C# method is not virtual by default. Overriding a method is a useful programming concept.. } Virtual methods allow you to call different versions of the same method. Example: namespace System { class Object { public virtual string ToString() { .. Hiding a method is a means of replacing one method with another— the methods are usually unrelated and might perform totally different tasks. } .

If the base class method is not virtual and you try to override it. return type. nest types (enum. they must have the same name. and the same return type. . you declare methods exactly as in a class or a struct. the same parameter types. private. The interface represents how you want an object to be used. structs. Exactly how the method is implemented is not a concern of the interface. and you replace the method body with a semicolon. 5) If the derived class does not declare the method by using the override keyword. and parameters of the method are.. } You preface the name of your interfaces with a capital I. } } There are some important rules you must follow when declaring polymorphic methods by using the virtual and override keywords: 1) You're not allowed to declare a private method by using the virtual or override keyword. Example: interface IComparable { int CompareTo(object obj). You cannot use inherit an interface. delegates) inside an interface. classes. rather than how it happens to be implemented at a particular moment in time. The interface tells you only what the name. interfaces. To declare an interface.. it does not override the base class method. constructors. access modifier. except that you never specify an access modifier (no public.public override string Name() { . or protected access). 3) The two methods must have the same access. INTERFACE An interface allows you to completely separate the name of a method from its implementation. destructors. 2) The two methods must be identical. you use the interface keyword instead of the class or struct keyword. 6) An override method is implicitly virtual and can itself be overridden in a further derived class. 4) You can only override a virtual method. That is. The restrictions on interfaces are u cannot have fields (not even static fields). Inside the interface.

3) The method name is prefaced by the name of the interface. C# does not distinguish between the base class and the interface by using keywords as Java does. the method should not have an access qualifier. A class can extend another class and implement an interface at the same time. 4) If you are using explicit interface implementation. the class will not compile. } } Here IToken is an interface defines as interface IToken { string Name(). you declare a class or struct that inherits from the interface and implements all the interface methods. whereas omitting the interface name allows this behavior.Name() { . followed by a comma. Example: class Token : IToken { .. you must ensure that each method matches its corresponding interface method exactly i.. Without using explicit interface implementation it would not be possible to distinguish which method implements part of which interface if multiple interfaces contain methods with the same names. 1) The method names and return types match 2) Any parameters declared match even the ref and out parameters... All methods implementing an interface are publicly accessible. If there is any difference between the interface definition and its declared implementation. } When you implement an interface. return types.To implement an interface. and parameters. . This is known as explicit interface implementation. followed by the interface. Advantages of Explicit Interface implementation: A method defined by using explicit interface implementation cannot be declared as virtual. In this case. The base class is named first.e. string IToken.

To declare that you're not allowed to create instances of a class. IToken. } private string name. you must explicitly declare that the class is abstract. A class must still implement all the methods it inherits from all its interfaces. Multiple Inheritances: A class can have at most one base class. An interface is not allowed to inherit from any kind of class. The best method is to use abstraction of common functionality. } public string Name() { return name. An abstract class internally is a virtual method. Abstract class must be overridden.You can reference an object by using a variable defined as an interface that its class implements. . but is allowed to implement an unlimited number of interfaces. } ABSTRACT CLASS Interfaces could be implemented by many different classes. whereas an interface is all about usage. } An abstract class is all about common implementation. but an interface is allowed to inherit other interfaces. by using the abstract keyword. IVisitable { . Example: class IdentifierToken : DefaultTokenImpl. Hence its quite common for parts of the derived classes to share common implementations. Abstract class cannot be instantiated but can only be inherited.name = name. This is a good solution but not the right one. To avoid the repetition of code is build a new class with the common implementation... Example: abstract class DefaultTokenImpl { public DefaultTokenImpl(string name) { this.

Sealed classes add another level of strictness during compile-time. } A sealed class cannot declare any virtual methods. C# allows you to use the sealed keyword to prevent a class from being used as a base class if you decide that it should not be. improve memory usage and trigger certain optimizations that improve run-time efficiency.. but extending the concept of data type from earlier programming languages to associate behavior most strongly with the data. structuring them to simplify a complex set of relationships. it is called Polymorphism. and "communicate" with other objects in the system. you are knowingly writing something that will be inherited from in the future. When it proceeds in the opposite direction. it is called Delegation or Inheritance. report on and change their state. The sole purpose of the virtual keyword is to declare that this is the first implementation of a method that you intend to override in a derived class. POLYMORPHISM (LATE BINDING OR DYNAMIC BINDING) . inside the types or classes. is the beginning of abstraction. ABSTRACTION Abstraction is the facility to define objects that represent abstract "actors" that can perform work. meaning the programmer cannot derive a new class from it nor the method can be overridden. enabling objects of different types to be substituted. You can only seal an override method. IToken { . Sealed method: You can also use the sealed keyword to declare that an individual method is sealed. The term information hiding refers to the hiding of state details. but a sealed class cannot be derived from. This means that a derived class cannot then override the sealed method.. A sealed class does not allow a programmer to use the class as a base class. Example: sealed class LiteralToken : DefaultTokenImpl.SEALED CLASS Using inheritance is not always easy and requires forethought. Fortunately. Unless you consciously design a class with the intention of using it as a base class. it's extremely unlikely that it will function very well as a base class. and standardizing the way that different data types interact. When abstraction proceeds into the operations defined. If you create an interface or an abstract class.

that is. to work this way. However. OVERLOADING If two identifiers have the same name and are declared in the same scope. polymorphism means that if class B inherits from class A. each one according to an appropriate type-specific behavior. Overloading is primarily useful when you need to perform the same operation on different data types. for example. This is called late binding or dynamic binding. or when the types of the parameters differ. it can do some of the things that class A does differently. First. list concatenation. GARBAGE COLLECTION GC CONCEPTS Object creation is really a two-phase process. it doesn’t have to inherit everything about class A. In other words. they are said to be overloaded. you can supply a comma-separated list of arguments. and the number and type of the arguments is used by the compiler to select one of the overloaded methods. In practical terms. may be used to perform integer addition. float addition. The language must therefore overload the concatenation operator. This helps improve code readability.Polymorphism lets you treat derived class members just like their parent class’s members. This capability is allowed so that. you can't declare two methods with the same name that differ only in their return type. to perform several different functions depending on the implementation. when you call a method. so this behavior can be implemented at run time. you can't overload the return type of a method. The "+" operator. Any two subclasses of Number. This means that the same “verb” can result in different actions as appropriate for a specific class. note that although you can overload the parameters of a method. You can overload a method when the different implementations have different sets of parameters. so controlling code can issue the same command to a series of objects and get appropriately different results from each one. the new operation has to allocate some raw memory from the heap. when they have the same name but a different number of parameters. the new operation has to convert the raw memory into . such as Integer and Double. Second. "+". The programmer (and the program) does not have to know the exact type of the object in advance. Overloading Polymorphism is the use of one method signature. You have no control over this phase of an object's creation. or string concatenation. are expected to add together properly in an OOP language. Polymorphism is the ability of objects belonging to different types to respond to method calls of the same name. or one operator such as "+".

the raw memory has to be given back to the heap. The runtime has to keep track of all these references. 2) You'd try to destroy an active object. You can control this phase this by using a constructor. the lifetime of an object cannot be tied to a particular reference variable. other references (such as ref) might still exist. Like object creation. If it was your responsibility to destroy objects. Either way. You could quite easily run out of memory. it has to initialize the object. Once again. all outstanding objects will be destroyed. you have no control over this phase. 3) You'd try and destroy the same object more than once. When a program ends. Therefore. sooner or later one of the following situations would arise: 1) You'd forget to destroy the object. The process of destroying an object and returning memory back to the heap is known as garbage collection. it would be a dangling reference.an object. depending on the code in the destructor. An object can only be destroyed when all the references to it have disappeared. You do this by writing a destructor. This would mean that the object's destructor (if it had one) would not be run. the memory that the object lived in has to be reallocated. Second. First. and memory would not be reallocated back to the heap. object destruction is also a two-phase process. 2) Each object is destroyed exactly once. the outcome of using dangling reference would be undefined. In C#. There just isn't any syntax to do it. An object can have as many references as possible. Instead. tidying up would not occur. 3) Each object is destroyed only when it becomes unreachable. you have to perform some tidying up. . when no references refer to the object. that is. The dangling reference would end up referring either to unused memory or possibly to a completely different object in the same piece of memory. If a class held a reference to a destroyed object. The garbage collector guarantees the following: 1) Each object will be destroyed and its destructors run. If the one of the reference disappears (by going out of scope). This might or might not be disastrous. The two phases of destruction exactly mirror the two phases of creation. you can never destroy an object yourself. the garbage collector is responsible for destroying objects for you.

instanceCount--. } ~Tally() { this. FINALIZE & DISPOSE FINALIZE You can use a destructor to perform any tidying up required when an object is garbage collected.The garbage collector runs in its own thread and can execute only at certain times (typically when your application reaches the end of a method). it also updates any references to the object. } . 2) It checks whether any of the unreachable objects has a destructor that needs to be run (a process called finalization). it cannot do this while objects are in use. This is because the garbage collector may need to move objects around and update object references. 4) At this point. it allows other threads to resume. The garbage collector builds this map very carefully and makes sure that circular references do not cause an infinite recursion. here's a simple class that counts the number of live instances by incrementing a static count in the constructor and decrementing a static count in the destructor: class Tally { public Tally() { this. Any unreachable object that requires finalization is placed in a special queue called the freachable queue (pronounced F-reachable). It does this by repeatedly following reference fields inside objects. While it runs. thus defragmenting the heap and freeing memory at the top of the heap.instanceCount++. The steps that the garbage collector takes are as follows: 1) It builds a map of all reachable objects. The syntax for writing a destructor is a tilde (~) followed by the name of the class. 5) It finalizes the unreachable objects that require finalization (now in the freachable queue) in a separate thread. other threads running in your application will temporarily halt. 3) It deallocates the remaining unreachable objects (those that don't require finalization) by moving the reachable objects down the heap. When the garbage collector moves a reachable object. For example. Any object not in this map is deemed to be unreachable.

} // compile-time error } 2) You cannot declare an access modifier (such as public) for a destructor. The compiler translates the following destructor: class Tally { ~Tally() { . } . private static int instanceCount = 0..Finalize().. This is because you never call the destructor yourself—the garbage collector does.public static int InstanceCount() { return this. and it cannot take any parameters. } } } The compiler-generated Finalize method contains the destructor body inside a try block.instanceCount... } finally { base. } // compile-time error 3) You never declare a destructor with parameters. so garbage collection does not apply. public ~Tally() { . Again.. this is because you never call the destructor yourself. } // compile-time error The compiler automatically translates a destructor into an override of the Object. ~Tally(int parameter) { . } There are some very important restrictions that apply to destructors: 1) You cannot declare a destructor in a struct.. A struct is a value type that lives on the stack and not the heap....Finalize method. } } Into this: class Tally { protected override void Finalize() { try { .. This ensures that .. followed by a finally block that calls the base class Finalize. struct Tally { ~Tally() { ..

You can't override Finalize yourself and you can't call Finalize yourself. } } This using statement is precisely equivalent to the following translation: { TextReader reader = new StreamReader(filename). The syntax for a using statement is as follows: using ( type variable = initialization ) embeddedStatement Example: using (TextReader reader = new StreamReader(filename)) { string line. you can call it explicitly and thereby control when the resource is released. and they need to be released as soon as possible. In these situations.ReadLine()) != null) { Console.WriteLine(line). It's important to realize that only the compiler can make this translation. and this object will be destroyed when the using statement block finishes.a destructor always calls its base class destructor. Scarce resources need to be released.ReadLine()) != null) { Console. The using statement provides a clean mechanism for controlling the lifetimes of resources. If a class has a disposal method. while ((line = reader. DISPOSE Sometimes it's inadvisable to release a resource in a destructor. while ((line = reader.WriteLine(line). try { string line. A disposal method is a method that disposes of a resource. .Dispose(). } } finally { if (reader != null) { ((IDisposable)reader). your only option is to release the resource yourself. You can create an object. some resources are just too valuable and too scarce to lie around unreleased for arbitrary lengths of time.

Exception. However. or implement the IDisposable interface? A call to a destructor will happen but you just don't know when. Who is a protected class-level variable available to? It is available to any sub-class (a class inheriting this class). What’s the top . What’s the C# syntax to catch any possible exception? A catch block that catches the exception of type System. You can also omit the parameter data type in this case and just write catch {}. because it relies on the programmer remembering to write a using statement. The IDisposable interface lives in the System namespace and contains just one method called Dispose: namespace System { interface IDisposable { void Dispose(). but you just can't be sure that it will actually happen. INTERVIEW QUESTIONS Does C# support multiple-inheritance? Yes. This acts as a useful backup. it is possible to ensure that the Dispose method always runs by calling it from the destructor. Describe the accessibility modifier “protected internal”. but they are not accessible. } } When writing a class. Are private class-level variables inherited? Yes. they are inherited. It is available to classes that are within the same assembly and derived from the specified base class. should you write a destructor.NET class that everything is derived from? System.} } } The variable you declare in a using statement must be of a type that implements the IDisposable interface. Although they are not visible or accessible via the class interface. On the other hand you know exactly when a call to the Dispose method happens.Object Will the finally block get executed if an exception has not occurred? Yes. .

then why not write the proper code to handle that error instead of passing a new Exception object to the catch block? Throwing your own exceptions signifies some design flaws in the project. What’s an abstract class? A class that cannot be instantiated. Can multiple catch blocks be executed for a single try statement? No. and are therefore public by default. The keyword “sealed” will prevent the class from being inherited. When the class itself is inherited from an abstract class. Why can’t you specify the accessibility modifier for methods inside the interface? They all must be public.there is no implementation. and events. and defined as separate entities from classes. all methods are abstract . In an interface class. no accessibility modifiers are allowed. define a set of properties. like classes. An abstract class may have accessibility modifiers.Why is it a bad idea to throw your own exceptions? Well. Can you prevent your class from being inherited by another class? Yes. Once the proper catch block processed. They are implemented by classes. 2. In an abstract class some methods can be concrete. When do you absolutely have to declare a class as abstract? 1. Make the method sealed. An abstract class is essentially a blueprint for a class without any implementation. methods. .NET does support multiple interfaces. What is an interface class? Interfaces. But unlike classes. control is transferred to the finally block (if there are any). interfaces do not provide implementation. . Can you allow a class to be inherited. but prevent the method from being over-ridden? Yes. An abstract class is a class that must be inherited and have the methods overridden. Can you inherit multiple interfaces? Yes. When at least one of the methods in the class is abstract. if at that point you know that an error has occurred. What’s the difference between an interface and abstract class? In an interface class. but not all base abstract methods have been overridden.

this is usually not a good practice. different order of parameters. you could call the garbage collector when you are done using a large object (or set of objects) to force the garbage collector to dispose of those very large objects from memory. and an inheriting class has a number of overloaded constructors.NET? As a good rule. What happens in memory when you Box and Unbox a value-type? Boxing converts a value-type to a reference-type. When should you call the garbage collector in . The signature of the virtual method must remain the same. If a base class has a number of overloaded constructors. you change the behavior of the method for the derived class. can you enforce a call from an inherited constructor to a specific base constructor? Yes. you should not call the garbage collector. . However. Can you declare an override method to be static if the original method is not static? No.What is the difference between a Struct and a Class? Structs are value-type variables and are thus saved on the stack. Overloading a method simply involves having another method with the same name within the class. The data type of the value parameter is defined by whatever data type the property is declared as. What does the keyword “virtual” declare for a method or property? The method or property can be overridden. How is method overriding different from method overloading? When overriding a method. and then keyword base (parameter list to invoke the appropriate constructor) in the overloaded constructor definition inside the inherited class. thus storing the object on the heap. What’s the implicit name of the parameter that gets passed into the set method/property of a class? Value. Unboxing converts a reference-type to a value-type. However. (Note: Only the keyword virtual is changed to keyword override) What are the different ways a method can be overloaded? Different parameter data types. different number of parameters. just place a colon. additional overhead but faster retrieval. How do you convert a value-type to a reference-type? Use Boxing. thus storing the value on the stack. Another difference is that structs cannot inherit.

NET runtime offer deterministic destruction? Because of the garbage collection algorithm.NET a problem? It's certainly an issue that affects component design. The implication of this algorithm is that the runtime doesn't get notified immediately when the final reference on an object goes away . The .unfortunately the runtime offers no help with this. you are effectively relying on the garbage collector to call the final release on your object. This concept is not new to . However. The garbage collector offers no guarantees about the time when an object will be destroyed and its memory reclaimed. database locks). When using a COM object from managed code.it only finds out during the next sweep of the heap. Normally heap exhaustion is the trigger for a collection sweep. Is it true that objects don't always get destroyed immediately when the last reference goes away? Yes. If you have objects that maintain expensive or scarce resources (e. Futhermore. Microsoft recommend that you provide a method called Dispose() for this purpose.NET . Why doesn't the . Does non-deterministic destruction affect the usage of COM objects from managed code? Yes.Java and many other languages/runtimes have used garbage collection for some time.g.in a distributed system who calls the Dispose() method? Some form of referencecounting or ownership-management mechanism is needed to handle distributed objects .What does Dispose method do with the connection object? Deletes it from the memory What is garbage collection? Garbage collection is a system whereby a run-time component takes responsibility for managing the lifetime of objects and the heap memory that they occupy. you need to provide some way for the client to tell the object to release the resource when it is done.NET garbage collector works by periodically running through a list of all the objects that are currently being referenced by an application. Is the lack of deterministic destruction in . If your COM object holds onto an expensive resource which is only cleaned-up after the . this type of algorithm works best by performing the garbage collection sweep as rarely as possible. this causes problems for distributed objects . All the objects that it doesn't find during this search are ready to be destroyed and the memory reclaimed.

I've heard that Finalize methods should be avoided. Do I have any control over the garbage collection algorithm? . Given the limitations of the garbage collection algorithm this seems like a pretty reasonable approach. // Cleanup activities GC. } ~CTest() { // C# syntax hiding the Finalize() method Dispose().. and the garbage collector is relieved of its Finalizing duties by the call to SuppressFinalize(). the object's resources are freed. you may need to provide a new interface on your object which supports an explicit Dispose() method. Should I implement Finalize on my class? An object with a Finalize method is more work for the garbage collector than an object without one. Microsoft recommend the following pattern: public class CTest : IDisposable { public void Dispose() { . i. there is a reasonable chance that the object's resources will eventually get freed by the garbage collector calling Finalize(). there is no guarantee that a Finalize method will get called on an object. so it should never be relied upon to do clean-up of an object's resources. the client forgets to call Dispose().final release.SuppressFinalize(this). } } In the normal case the client calls Dispose(). Finally. In the worst case.e. so there are issues surrounding access to other objects from the Finalize method. Also there are no guarantees about the order in which objects are Finalized..

Use Performance Monitor to view them. the System.this forces the garbage collector to collect all unreferenced objects immediately.A little.GC class exposes a Collect method . . How can I find out what the garbage collector is doing? Lots of interesting statistics are exported from the .NET CLR xxx' performance counters.NET runtime via the '. For example.