Notes Oops and C#

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 14

Encapsulation Encapsulation binds together code and the data it manipulates and keeps them bot h safe from

outside interference and misuse. Encapsulation is a protective conta iner that prevents code and data from being accessed by other code defined outsi de the container. Inheritance Inheritance is the process by which one object acquires the properties of anothe r object. A type derives from a base type, taking all the base type members fiel ds and functions. Inheritance is most useful when you need to add functionality to an existing type. For example all .NET classes inherit from the System.Object class, so a class can include new functionality as well as use the existing obj ect's class functions and properties as well. Polymorphism Polymorphism is a feature that allows one interface to be used for a general cla ss of action. This concept is often expressed as "one interface, multiple action s". The specific action is determined by the exact nature of circumstances.

Classes and Objects Classes are special kinds of templates from which you can create objects. Each o bject contains data and methods to manipulate and access that data. The class de fines the data and the functionality that each object of that class can contain. A class declaration consists of a class header and body. The class header includ es attributes, modifiers, and the class keyword. The class body encapsulates the members of the class, that are the data members and member functions. The synta x of a class declaration is as follows: Attributes accessibility modifiers class identifier: baselist { body } Attributes provide additional context to a class, like adjectives; for example t he Serializable attribute. Accessibility is the visibility of the class. The def ault accessibility of a class is internal. Private is the default accessibility of class members. The following table lists the accessibility keywords; public ssembly. private protected Internal Internal protected current class. Public class is visible in the current and referencing a Visible inside current class. Visible inside current and derived class. Visible inside containing assembly. Visible inside containing assembly and descendent of the

Modifiers refine the declaration of a class. The list of all modifiers defined i n the table are as follows; Modifier sealed static unsafe Abstract abstract. Class can't be inherited by a derived class. Class contains only static members. The class that has some unsafe construct likes pointers. The instance of the class is not created if the Class is

The baselist is the inherited class. By default, classes inherit from the System .Object type. A class can inherit and implement multiple interfaces but doesn't support multiple inheritances.

Partial classes Typically, a class will reside entirely in a single file. where multiple developers need access to the same class, in multiple files can be beneficial. The partial keywords multiple source files. When compiled, the elements of the ined into a single assembly. However, in situations then having the class allow a class to span partial types are comb

There are some rules for defining a partial class as in the following; A partial type must have the same accessibility. Each partial type is preceded with the "partial" keyword. If the partial type is sealed or abstract then the entire class will be seal ed and abstract. In the following example we are adding two files, partialPart1.cs and partialPar t2.cs, and declare a partial class, partialclassDemo, in both classes. partialPart1.cs using System; namespace oops { public partial class partialclassDemo { public void method1() { Console.WriteLine("method from part1 class"); } } } partialPart2.cs

using System; namespace oops { public partial class partialclassDemo { public void method2() { Console.WriteLine("method from part2 class"); } } } And finally we are creating an instance of the partialclassDemo in the program.c s file as the following: Program.cs using System; namespace oops { class Program { static void Main(string[] args) { //partial class instance partialclassDemo obj = new partialclassDemo(); obj.method1(); obj.method2(); } } } Static classes A static class is declared using the "static" keyword. If the class is declared as static then the compiler never creates an instance of the class. All the memb er fields, properties and functions must be declared as static and they are acce ssed by the class name directly not by a class instance object. Constructor and Destructor A constructor is a specialized function that is used to initialize fields. A con structor has the same name as the class. Instance constructors are invoked with the new operator and can't be called in the same manner as other member function s. There are some important rules pertaining to constructors as in the following ; Classes with no constructor have an implicit constructor called the default constructor, that is parameterless. The default constructor assigns default valu es to fields. A public constructor allows an object to be created in the current assembly or referencing assembly. Only the extern modifier is permitted on the constructor.

A constructor returns void but does not have an explicitly declared return t ype. A constructor can have zero or more parameters. Classes can have multiple constructors in the form of default, parameter or both. Static Constructor A constructor can be static. You create a static constructor to initialize stati c fields. Static constructors are not called explicitly with the new statement. They are called when the class is first referenced. There are some limitations o f the static constructor as in the following; Static constructors are parameterless. Static constructors can't be overloaded. There is no accessibility specified for Static constructors. Destructor The purpose of the destructor method is to remove unused objects and resources. Destructors are not called directly in the source code but during garbage collec tion. Garbage collection is nondeterministic. A destructor is invoked at an unde termined moment. More precisely a programmer can't control its execution; rather it is called by the Finalize () method. Like a constructor, the destructor has the same name as the class except a destructor is prefixed with a tilde (~). The re are some limitations of destructors as in the following; Destructors are parameterless. A Destructor can't be overloaded. Destructors are not inherited. Destructors can cause performance and efficiency implications. using System; namespace oops { class customer { // Member Variables public int x, y; //constuctor for initializing fields customer() { Console.WriteLine("Fields inititalized"); x = 10; } //method for get field public void getData() { y = x * x; Console.WriteLine(y); }

//method to release resource explicitly public void Dispose() { Console.WriteLine("Fields cleaned"); x = 0; y = 0; } //destructor ~customer() { Dispose(); } //Entry point static void Main(string[] args) { //instance created customer obj = new customer(); obj.getData(); } } } Function Overloading Function overloading allows multiple implementations of the same function in a c lass. Overloaded methods share the same name but have a unique signature. The nu mber of parameters, types of parameters or both must be different. A function ca n't be overloaded on the basis of a different return type alone. Inheritance Inheritance is the process by which one object can acquire the properties of ano ther object. Inheritance is a "is a kind of" relationship and it supports the co ncept of classification in which an object needs only define those qualities tha t make it unique within the class. Inheritance involves a base class and a deriv ed class. The derived class inherits from the base class and also can override i nherited members as well as add new members to extend the base class. A base type represents the generalization, whereas a derived type represents a s pecification of an instance. Such as Employees that can have diverse types, such as hourly, salaried and temporary so in that case Employees is the general base class and hourly, salaried and temporary employee are specialized derived class es. Classes can inherit from a single class and one or more interfaces. When inherit ing from a class, the derived class inherits the members including the code of t he base class. The important point to remember is that Constructors and Destruct ors are not inherited from the base class. C# does not support multiple class inheritance but supports multilevel in herita nce C# does not support multiple class inheritance because : 1. if suppose there is class A with method Print(), and class B and Class C inhe rit class A and override the method Print() in both the child classes B and C wi th different implementation and the class D inherits both B,C then the compiler does not know which Print() method to execute this is known asthe Diamond proble

m A class cannot inherit from multiple base classes at the same time, whereas a cl ass can inherit from multiple interfaces at the same. So, since a class is capab le of inheriting from multiple interfaces at the same and if parent interfaces h appen to have a same method name then the class can be explicit about which inte rface method it is implementing using explicit interface implementation. Whereas with classes, we won't ever run into this situation. The syntax of inheritance is as in the following; Class derivedClass : baseClass, Iterface1, Interface2 { body } using System; namespace oops { //Base Class public class Father { public void FatherMethod() { Console.WriteLine("this property belong to Father"); } } //Derived class public class Child : Father { public void ChildMethod() { Console.WriteLine("this property belong to Child"); } } class Inheritance { //Entry point static void Main(string[] args) { Father fObj = new Father(); fObj.FatherMethod(); //Here Child object can access both class methods Child cObj = new Child(); cObj.FatherMethod(); cObj.ChildMethod(); } } } At line 11 , the Intellisense only shows the Father class functions but at line 15 to 16 the Child class object is able to access both class methods as in the f ollowing. We can create a class in the VB.Net language or another .NET supported language and can inherit them in a C# .Net class and vice versa. But a class developed in C++ or other unmanaged environment can't be inherited in .NET. Note: Cross-language and multiple inheritance is not supported by .NET

Accessibility Accessibility sets the visibility of the member to outside assemblies or derived types. The following table describes member accessibility;

Modifiers Derived Class private No public Yes protected No internal is assembly only) internal protected Yes Constructor in Inheritance

Outside Assembly No Yes No Yes ( this assembly only) Yes( this assembly only) Yes ( th

Constructors in a base class are not inherited in a derived class. A derived cla ss has a base portion and derived portion. The base portion initializes the base portion, and the constructor of the derived class initializes the derived porti on. The following is the syntax of a constructor in inheritance; Accessibility modifier classname(parameterlist1) : base(parameterlist2) { body } So the base keyword refers to the base class constructor, while parameterlist2 d etermines which overloaded base class constructor is called. In the following example, the Child class's constructor calls the single-argumen t constructor of the base Father class; C# code using System; namespace oops { //Base Class public class Father { //constructor public Father() { Console.WriteLine("Father class constructor"); } public void FatherMethod() { Console.WriteLine("this property belong to Father");

} } //Derived class public class Child : Father { public Child() : base() { Console.WriteLine("child class constructor"); } public void ChildMethod() { Console.WriteLine("this property belong to Child"); } } class Inheritance { //Entry point static void Main(string[] args) { //Here Child object can access both class methods Child cObj = new Child(); cObj.FatherMethod(); cObj.ChildMethod(); Console.ReadKey(); } } } At line 4, we are defining a base Father Class constructor and in the derived cl ass Child, at line 8 we are initializing it explicitly via base keyword. If we p ass any parameter in the base class constructor then we have to provide them in the base block of the child class constructor.

Virtual Methods By declaring a base class function as virtual, you allow/not forceable the funct ion to be overridden in any derived class. The idea behind a virtual function is to redefine the implementation of the base class method in the derived class as required. If a method is virtual in the base class then we have to provide the override keyword in the derived class. Neither member fields nor static function s can be declared as virtual. (Program dosent give error if the functions is not overriden) C# code using System; namespace oops { class myBase { //virtual function public virtual void VirtualMethod() { Console.WriteLine("virtual method defined in the base class");

} } class myDerived : myBase { // redifing the implementation of base class method public override void VirtualMethod() { Console.WriteLine("virtual method defined in the Derive class"); } } class virtualClass { static void Main(string[] args) { // class instance new myDerived().VirtualMethod(); Console.ReadKey(); } } } Abstract Classes C# allows both classes and functions to be declared abstract using the abstract keyword. You can't create an instance of an abstract class. An abstract member h as a signature but no function body and they must be overridden in any non-abstr act derived class. Abstract classes exist primarily for inheritance. Member func tions, properties and indexers can be abstract. A class with one or more abstrac t members must be abstract as well. Static members can't be abstract. In this example, we are declaring an abstract class Employess with a method disp layData() that does not have an implementation. Then we are implementing the dis playData() body in the derived class. One point to be noted here is that we have to prefixe the abstract method with the override keyword in the derived class. C# code using System; namespace oops { //abstract class public abstract class Employess { //abstract method with no implementation public abstract void displayData(); } //derived class public class test : Employess { //abstract class method implementation public override void displayData() { Console.WriteLine("Abstract class method"); } } class abstractClass { static void Main(string[] args)

{ // class instance new test().displayData(); } } } In 1. 2. 3. 4. 5. other world an abstract class needs abstract keyword before class abstract key word before method name abstract class can have fields abstract class can inherit from another abstract class ans interfaces abstract class can have access modifiers

If an abstract class has a method without abstract keyword it works ans executes and does not throw an error As soon as the method in abstract class is preceeded with abstract keyword the m ethod has to be overriden in the derived class using override thus abstract class can contain a normal defined method and an abstract but the abstract method must/forcefully be overriden using override keyword.

Interfaces Interfaces only provides the signatures of methods properties delegates and even ts. Only the names signature is sumthing which has no implementation. By default interfaces are public and they should be public as they are implement ed by other classes Runtime polymorphism In interfaces one must/forcefully implement the methods defined in interface and if not implemented the build will throw an error Best example for using interfaces is multiple databases In interface one does not need to use override funtion for the implementations o f methods An interface is a set of related functions that must be implemented in a derived class. Members of an interface are implicitly public and abstract. Interfaces a re similar to abstract classes. First, both types must be inherited; second, you cannot create an instance of either. Although there are several differences as in the following; An Abstract class can contain some implementations but an interface can't. An Interface can only inherit other interfaces but abstract classes can inhe rit from other classes and interfaces. An Abstract class can contain constructors and destructors but an interface can't. An Abstract class contains fields but interfaces don't. So the question is, which of these to choose? Select interfaces because with an interface, the derived type still can inherit from another type and interfaces a re more straightforward than abstract classes.

C# code using System; namespace oops { // interface public interface xyz { void methodA(); void methodB(); } // interface method implementation class test : xyz { public void methodA() { Console.WriteLine("methodA"); } public void methodB() { Console.WriteLine("methodB"); } } class interfaceDemo { static void Main(string[] args) { test obj = new test(); obj.methodA(); obj.methodB(); } } } An interface can be inherited from other interfaces as in the following: C# code public interface xyz { void methodA(); void methodB(); } public interface abc : xyz { void methodC(); } Sealed Classes Sealed classes are the reverse of abstract classes. While abstract classes are i nherited and are refined in the derived class, sealed classes cannot be inherite d. You can create an instance of a sealed class. A sealed class is used to preve nt further refinement through inheritance. Suppose you are a developer of a class library and some of the classes in the cl ass library are extensible but other classes are not extensible so in that case

those classes are marked as sealed. C# code using System; namespace oops { sealed class SealedClass { void myfunv(); } public class test : SealedClass //wrong. will give compilation error { } } Delegates These are type safe function pointers it holds a reference to a function i.e. po ints to the function. Delegate points to a function and when we invoke the deleg ate the function is also invoked Type safe: in the code below if the print method is returning a string and while writing a delegate you do not define a return type it will immediately give a r edline showing a error in other word it avoids bufferover run it does not allow use to do what is not m ent to do (tip:just used delegate keyword in the signature of the method) accesblity delegate returntype delegateName(parameters) using System; using System.Collections.Generic; using System.Text; namespace ConsoleApplication2 { public delegate void PrinDele(string a); class Program { public static void Main(string[] args) { PrinDele objDele = new PrinDele(Print); objDele("Hello"); } public static void Print(string t) { Console.WriteLine(t); } }

} Another way to implement delegate using System; using System.Collections.Generic; using System.Text; namespace ConsoleApplication2 { public delegate void PrinDele(string a); class Program { public static void Main(string[] args) { PrinDele objDele; objDele = Print; objDele.Invoke("Hello"); } public static void Print(string t) { Console.WriteLine(t); } }

} Used by framework implementers if you want to pass a function as a parameter pass the delegate as aparameter using System; using System.Collections.Generic; using System.Text; namespace ConsoleApplication2 { public delegate bool PromoteDel(Emp em); class Program { public static void Main(string[] args) { List<Emp> lis = new List<Emp>(); lis.Add(new Emp() { Name ="A",Yrs=5}); lis.Add(new Emp() { Name = "B", Yrs = 3 }); lis.Add(new Emp() { Name = "C", Yrs = 2 }); lis.Add(new Emp() { Name = "D", Yrs = 6 }); lis.Add(new Emp() { Name = "E", Yrs = 8 }); //emp => emp.Yrs is called lamda function Emp.promote(lis, emp => emp.Yrs >= 5); Console.ReadKey(); }

} public class Emp { public string Name{get;set;} public int Yrs { get; set; } public static void promote(List<Emp> emplist , PromoteDel prom) { foreach (Emp employee in emplist) { if (prom(employee)) { Console.WriteLine(employee.Name + " Promoted"); } } } }

} in the above example the Emp class becomes more flexible as we donot force the l ogic for promoting an employee it is given by the user.

You might also like