Вы находитесь на странице: 1из 8

Credit Suisse is a leading global financial services company, offering clients financial advice in all aspects of private banking,

investment banking and asset management.


A globally integrated bank with 153 years of tradition

What is an Abstract Class?


An abstract class is a special kind of class that cannot be instantiated. So the question is why we need a class that cannot be instantiated? An abstract class is only to be sub-classed (inherited from). In other words, it only allows other classes to inherit from it but cannot be instantiated. The advantage is that it enforces certain hierarchies for all the subclasses. In simple words, it is a kind of contract that forces all the subclasses to carry on the same hierarchies or standards.

What is an Interface?
An interface is not a class. It is an entity that is defined by the word Interface. An interface has no implementation; it only has the signature or in other words, just the definition of the methods without the body. As one of the similarities to Abstract class, it is a contract that is used to define hierarchies for all subclasses or it defines specific set of methods and their arguments. The main difference between them is that a class can implement more than one interface but can only inherit from one abstract class. Since C# doesnt support multiple inheritance, interfaces are used to implement multiple inheritance.

Both Together
When we create an interface, we are basically creating a set of methods without any implementation that must be overridden by the implemented classes. The advantage is that it provides a way for a class to be a part of two classes: one from inheritance hierarchy and one from the interface. When we create an abstract class, we are creating a base class that might have one or more completed methods but at least one or more methods are left uncompleted and declared abstract. If all the methods of an abstract class are uncompleted then it is same as an interface. The purpose of an abstract class is to provide a base class definition for how a set of derived classes will work and then allow the programmers to fill the implementation in the derived classes. There are some similarities and differences between an interface and an abstract class that I have arranged in a table for easier comparison: Feature Multiple inheritance Default implementation Interface A class may inherit several interfaces. An interface cannot Abstract class A class may inherit only one abstract class. An abstract class can

Feature

Interface provide any code, just the signature.

Abstract class provide complete, default code and/or just the details that have to be overridden. An abstract class can contain access modifiers for the subs, functions, properties An abstract class defines the core identity of a class and there it is used for objects of the same type.

Access Modfiers

An interface cannot have access modifiers for the subs, functions, properties etc everything is assumed as public Interfaces are used to define the peripheral abilities of a class. In other words both Human and Vehicle can inherit from a IMovable interface. If various implementations only share method signatures then it is better to use Interfaces.

Core VS Peripheral

Homogeneity

If various implementations are of the same kind and use common behaviour or status then abstract class is better to use.

Speed

Requires more time to Fast find the actual method in the corresponding classes. If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method. If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly.

Adding functionality (Versioning)

Fields and Constants

No fields can be defined in An abstract class can have interfaces fields and constrants defined

What is the difference between interface and abstract class?

* interface contains methods that must be abstract; abstract class may contain concrete methods. * interface contains variables that must be static and final; abstract class may contain non-final and final variables. * members in an interface are public by default, abstract class may contain non-public members. * interface is used to "implements"; whereas abstract class is used to "extends". * interface can be used to achieve multiple inheritance; abstract class can be used as a single inheritance. * interface can "extends" another interface, abstract class can "extends" another class and "implements" multiple interfaces. * interface is absolutely abstract; abstract class can be invoked if a main() exists. * interface is more flexible than abstract class because one class can only "extends" one super class, but "implements" multiple interfaces. * If given a choice, use interface instead of abstract class.

Difference between classes and structs in C#

1. Value type vs Reference type: Structs are value type and classes are reference type.
o Whenever a struct object is assigned to another struct object a copy is created. In case of classes the same operation results in two references referring to same object: For example a.x 10; b a; a.x 20; cout << b.x will display '10' if a and b are struct objects and it will display '20' if a and b are class objects. o Boxing of a struct object creates a copy of the object in a different type whereas boxing a class object creates a reference (of different type) to the same object. o o Since structs are value type it is not possible to assign null to a struct object. When a struct object is passed to a function as a parameter it is passed by value unless specifically marked as 'ref' or 'out' parameter.

2. Inheritance: Inheritance is not allowed for structs.


o All struct types implicitly inherit from System.ValueType and they are implicitly sealed. o The keywords related to inheritance concepts are not allowed for structs. For example abstract protected virtual override etc.

3. Initialization: Structs cannot have default constructor.

All struct member variables of value type are initialized to their default values and reference member variables are initialized to null.

Field initializers (initialization in the member variable declaration line like int a 0; ) is also not allowed for structs.

4. Destructor: Structs cannot declare a destructor.


5. Meaning of 'this': o For a struct instance constructor (parameterized) 'this' is treated as an out parameter. o o o For other member functions it is treated as a 'ref' parameter. So it is possible to assign to 'this' and change the current object.

In case of a class 'this' is considered as a value so it is not possible to assign to 'this' from inside a class.

Since 'this' is a 'ref' or 'out' parameter it must be definitely assigned at every point where it is used.

Use a class when object identity is more important than value. Use a struct when the value contained by an instance is more important than instance identity. Structs are usually (not always) simpler types. Struct variables directly contain their values, so when you pass a struct instance as a parameter, it can be more expensive than passing an instance of a reference type, due to the copying costs. Structures are value types; classes are reference types. Structures use stack allocation; classes use heap allocation. All structure members are Public by default; class variables and constants are Private by default, while other class members are Public by default. This behavior for class members provides compatibility with the Visual Basic 6.0 system of defaults. A structure must have at least one nonshared variable or event member; a class can be completely empty. Structure members cannot be declared as Protected; class members can. A structure procedure can handle events only if it is a Shared Sub procedure, and only by means of the AddHandler statement; any class procedure can handle events, using either the Handles keyword or the AddHandler statement. Structure variable declarations cannot specify initializers, the New keyword, or initial sizes for arrays; class variable declarations can. Structures implicitly inherit from the ValueType class and cannot inherit from any other type; classes can inherit from any class or classes other than

A delegate is a type-safe object that can point to another method (or possibly multiple methods) in the application, which can be invoked at later time. Delegates also can invoke methods Asynchronously. A delegate type maintains three important pices of information : 1. The name of the method on which it make calls. 2. Any argument (if any) of this method. 3. The return value (if any) of this method. Defining a Delegate in C# when you want to create a delegate in C# you make use of delegate keyword. The name of your delegate can be whatever you desire. However, you must define the delegate to match the signature of the method it will point to. fo example the following delegate can point to any method taking two integers and returning an integer. public delegate int DelegateName(int x, int y); A Delegate Usage Example namespace MyFirstDelegate { //This delegate can point to any method, //taking two integers and returning an //integer. public delegate int MyDelegate(int x, int y); //This class contains methods that MyDelegate will point to. public class MyClass { public static int Add(int x, int y) { return x + y; } public static int Multiply(int x, int y) { return x * y; } } class Program { static void Main(string[] args) { //Create an Instance of MyDelegate //that points to MyClass.Add(). MyDelegate del1 = new MyDelegate(MyClass.Add); //Invoke Add() method using the delegate. int addResult = del1(5, 5); Console.WriteLine("5 + 5 = {0}\n", addResult);

} } }

//Create an Instance of MyDelegate //that points to MyClass.Multiply(). MyDelegate del2 = new MyDelegate(MyClass.Multiply); //Invoke Multiply() method using the delegate. int multiplyResult = del2(5, 5); Console.WriteLine("5 X 5 = {0}", multiplyResult); Console.ReadLine();

Delegate ability to Multicast Delegate's ability to multicast means that a delegate object can maintain a list of methods to call, rather than a single method if you want to add a method to the invocation list of a delegate object , you simply make use of the overloaded += operator, and if you want to remove a method from the invocation list you make use of the overloaded operator -= . Note: The Multicast delegate here contain methods that return void, if you want to create a multicast delegate with return type you will get the return type of the last method in the invocation list. A Multicast Delegate Example
namespace MyMulticastDelegate { //this delegate will be used to call more than one //method at once public delegate void MulticastDelegate(int x, int y); //This class contains methods that MyDelegate will point to. public class MyClass { public static void Add(int x, int y) { Console.WriteLine("You are in Add() Method"); Console.WriteLine("{0} + {1} = {2}\n", x, y, x + y); } public static void Multiply(int x, int y) { Console.WriteLine("You are in Multiply() Method"); Console.WriteLine("{0} X {1} = {2}", x, y, x * y); } } class Program { static void Main(string[] args) { //Create an Instance of MulticastDelegate

//that points to MyClass.Add(). MulticastDelegate del = new MulticastDelegate(MyClass.Add); //using the same instance of MulticastDelegate //to call MyClass.Multibly() by adding it to it's //invocation list. del += new MulticastDelegate(MyClass.Multiply); //Invoke Add() and Multiply() methods using the delegate. //Note that these methods must have a void return vlue Console.WriteLine("****calling Add() and Multibly() Methods.****\n\n"); del(5, 5); //removing the Add() method from the invocation list del -= new MulticastDelegate(MyClass.Add); Console.WriteLine("\n\n****Add() Method removed.****\n\n"); //this will invoke the Multibly() method only. del(5, 5); } } }

Ready Only and Constant


Readonly and const both are same they can never be modified. But readonly allows initializing variables at run time. const must be initialized to a compile time constant. Ex: public readonly DateTime dt = DateTime.Now public const int i = 2;

public class MyClass { //Initialized at Run time readonly int readonlyInt; //Initialized at Compile Time const int constint = 0; public MyClass(int n) { readonlyInt = n; } }

Вам также может понравиться