1. Inheritance
using System;
public class Parent
{
string parentString;
public Parent()
{
Console.WriteLine("Parent Constructor.");
}
public Parent(string myString)
{
parentString = myString;
Console.WriteLine(parentString);
}
public void print()
{
Console.WriteLine("I'm a Parent Class.");
}
}
.
2. public class Child : Parent
{
public Child() : base("From Derived")
{
Console.WriteLine("Child Constructor.");
}
public new void print()
{
base.print();
Console.WriteLine("I'm a Child Class.");
}
public static void Main()
{
Child child = new Child();
child.print();
}
}
4. Class and its members in C#.NET
•
To create a class, use the keyword class and has the following syntax.
• [Access Modifier] class ClassName
• {
• -
• -
• -
• }
• A class can be created with only two access modifiers, public and internal.
Default is public. When a class is declared as public, it can be accessed
within the same assembly in which it was declared as well as from out side
the assembly. But when the class is created as internal then it can be
accessed only within the same assembly in which it was declared.
5. Class and its members in C#.NET
Members of a Class
A class can have any of the following members.
• Fields
• Properties
• Methods
• Events
• Constructors
• Destructor
• Operators
• Indexers
• Delegates
• Fields : A field is the variable created within the class and it is used to store data of
the class. In general fields will be private to the class for providing security for the
data
• Syntax : [Access Modifier] DataType Fieldname;
6. Class and its members in C#.NET
• Properties : A property is a method of the class that appears to the
user as a field of the class. Properties are used to provide access to
the private fields of the class. In general properties will be public.
• Syntax : [Access Modifier] DataType PropName
• {
• Get
• {
• }
• Set
• {
• }
• }
• A property contains two accessors, get and set.
7. Class and its members in C#.NET
• When user assigns a value to the property, the set accessor of the property will be
automatically invoked AND VALUE ASSIGNED to the property will be passed to set
accessor with the help of an implicit object called value. Hence set accessor is used
to set the value to private field. Within the set accessor you can perform validation
on value before assigning it to the private field.
When user reads a property, then the get accessor of the property is automatically
invoked. Hence get accessor is used to write the code to return the value stored in
private field.
• Readonly Property : There may be a situation where you want to allow the user to
read the property and not to assign a value to the property. In this case property
has to be created as readonly property and for this create the property only with
get accessor without set accessor.
• Syntax : [Access Modifier] DataType PropName
• {
• Get
• {
• }
• }
8. Class and its members in C#.NET
• Writeonly Property : There may be a situation where you want to
allow the user to assign a value to the property and not to read the
property. In this case property has to be created as writeonly
property and for this create the property only with set accessor
without get accessor.
• Syntax : [Access Modifier] DataType PropName
• {
• Set
• {
• }
• }
• Methods
• Methods are nothing but functions created within the class.
Functions are used to specify various operations that can be
performed on data represented by the class.
9. Class and its members in C#.NET
• class MyClass
{
private int x;
public void SetX(int i)
{
x = i;
}
public int GetX()
{
return x;
}
}
class MyClient
{
public static void Main()
{
MyClass mc = new MyClass();
mc.SetX(10);
int xVal = mc.GetX();
Console.WriteLine(xVal);//Displays 10
}
}
10. Example program for property and
method of a class
• using System;
namespace example
{
class programCall
{
int n; //instance variable
//property nn to access private field n
public int nn
{
set { n = value; }
get { return n; }
}
11. Example program for property and
method of a class
• //declare a method to print field n value
//by default members of class will be private , so to access explictly declare public
public void print()
{
Console.WriteLine(n);
}
}
class MainClass
{
static void Main(string[] args)
{
//creating object to class programcall
programCall objpc = new programCall();
12. Example program for property and
method of a class
• //instance members can only be accessed with an instance
objpc.nn = 99999;
objpc.print();
Console.Read();
}
}
}
•
Output
99999
13. Constructor in C#.NET
• A special method of the class that will be automatically invoked when an instance
of the class is created is called as constructor.
Constructors are mainly used to initialize private fields of the class while creating
an instance for the class.
When you are not creating a constructor in the class, then compiler will
automatically create a default constructor in the class that initializes all numeric
fields in the class to zero and all string and object fields to null.
To create a constructor, create a method in the class with same name as class and
has the following syntax.
[Access Modifier] ClassName([Parameters])
• {
• }
•
14. Constructor in C#.NET
• Example program using Constructors
using System;
class ProgramCall
{
int i, j;
//default contructor
public ProgramCall()
{
i = 45;
j = 76;
}
15. Constructor in C#.NET
• public static void Main()
{
//When an object is created , contructor is called
ProgramCall obj = new ProgramCall();
Console.WriteLine(obj.i);
Console.WriteLine(obj.j);
Console.Read();
}
}
•
OUTPUT
45
76
16. Constructor types with example
programs in C#.NET
• A special method of the class that will be
automatically invoked when an instance of the
class is created is called as constructor.
Constructors can be classified
• Default Constructor
• Parameterized Constructor
• Copy Constructor
• Private Constructor
17. Constructor types
• Default Constructor : A constructor without any parameters is called as default constructor.
Drawback of default constructor is every instance of the class will be initialized to same values and
it is not possible to initialize each instance of the class to different values.
Example for Default Constructor
Parameterized Constructor : A constructor with at least one parameter is called as parameterized
constructor. Advantage of parameterized constructor is you can initialize each instance of the class
to different values.
Example for Parameterized Constructor
• using System;
namespace ProgramCall
{
class Test1
{
//Private fields of class
int A, B;
18. Constructor types
• //default Constructor
public Test1()
{
A = 10;
B = 20;
}
//Paremetrized Constructor
public Test1(int X, int Y)
{
A = X;
B = Y;
}
//Method to print
public void Print()
{
Console.WriteLine("A = {0}tB = {1}", A, B);
}
}
19. Constructor types
•
class MainClass
{
static void Main()
{
Test1 T1 = new Test1(); //Default Constructor is called
Test1 T2 = new Test1(80, 40); //Parameterized Constructor is called
T1.Print();
T2.Print();
Console.Read();
}
}
}
•
Output
A = 10 B = 20
A = 80 B = 40
20. Constructor types
• Copy Constructor : A parameterized constructor that contains a parameter of same class type is
called as copy constructor. Main purpose of copy constructor is to initialize new instance to the
values of an existing instance.
Example for Copy Constructor
using System;
namespace ProgramCall
{
class Test2
{
int A, B;
public Test2(int X, int Y)
{
A = X;
B = Y;
}
21. Constructor types
• //Copy Constructor
public Test2(Test2 T)
{
A = T.A;
B = T.B;
}
public void Print()
{
Console.WriteLine("A = {0}tB = {1}", A, B);
}
}
class CopyConstructor
{
static void Main()
{
22. Constructor types
• Test2 T2 = new Test2(80, 90);
//Invoking copy constructor
Test2 T3 = new Test2(T2);
T2.Print();
T3.Print();
Console.Read();
}
}
}
•
Output
A = 80 B = 90
A = 80 B = 90
23. Constructor types
Private Constructor : You can also create a constructor as
private. When a class contains at least one private
constructor, then it is not possible to create an instance for
the class. Private constructor is used to restrict the class
from being instantiated when it contains every member as
static.
Some unique points related to constructors are as follows
• A class can have any number of constructors.
• A constructor doesn’t have any return type even void.
• A static constructor can not be a parameterized
constructor.
• Within a class you can create only one static constructor.
24. Destructor in C#.NET
•
A destructor is a special method of the class that is automatically invoked while an instance of the
class is destroyed. Destructor is used to write the code that needs to be executed while an instance
is destroyed. To create a destructor, create a method in the class with same name as class preceded
with ~ symbol.
Syntax :
~ClassName()
{
• }
Example : The following example creates a class with one constructor and one destructor. An
instance is created for the class within a function and that function is called from main. As the
instance is created within the function, it will be local to the function and its life time will be
expired immediately after execution of the function was completed.
25. Destructor in C#.NET
• using System;
namespace ProgramCall
{
class myclass
{
public myclass()
{
Console.WriteLine("An Instance Created");
}
//destructor
~myclass()
{
Console.WriteLine("An Instance Destroyed");
}
}
26. Destructor in C#.NET
•
class Destructor
{
public static void Create()
{
myclass T = new myclass();
}
static void Main()
{
Create();
GC.Collect();
Console.Read();
}
}
}
• Output
An Instance Created
An Instance Destroyed
27. Polymorphism in C#
• When a message can be processed in different ways is called
polymorphism. Polymorphism means many forms.
• Polymorphism is one of the fundamental concepts of OOP.
• Polymorphism provides following features:
• It allows you to invoke methods of derived class through base class
reference during runtime.
• It has the ability for classes to provide different implementations of
methods that are called through the same name.
• Polymorphism is of two types:
• Compile time polymorphism/Overloading
• Runtime polymorphism/Overriding
• Compile Time Polymorphism
• Compile time polymorphism is
method and
operators overloading.
• In method overloading method performs the different task at the different
input parameters.
28. Polymorphism in C#
• Runtime Time Polymorphism
• Runtime time polymorphism is done using inheritance and virtual
functions. Method overriding is called runtime polymorphism. It is also
called late binding.
• When overriding a method, you change the behavior of the method for
the derived class. Overloading a method simply involves having another
method with the same prototype.
• Caution: Don't confused method overloading with method
overriding, they are different, unrelated concepts. But they sound similar.
• Method overloading has nothing to do with inheritance or virtual
methods.
• Following are examples of methods having different overloads:
• void area(int side);
• void area(int l, int b);
• void area(float radius);
29. Polymorphism in C#
• Practical example of Method Overloading (Compile Time Polymorphism)
• using System;
• namespace method_overloading
• {
• class Program
• {
• public class Print
• {
• public void display(string name)
• {
• Console.WriteLine("Your name is : " + name);
• }
• public void display(int age, float marks)
• {
• Console.WriteLine("Your age is : " + age);
• Console.WriteLine("Your marks are :" + marks);
• }
30. Polymorphism in C#
• }
• static void Main(string[] args)
• {
• Print obj = new Print();
• obj.display("George");
• obj.display(34, 76.50f);
• Console.ReadLine();
• }
• }
• }
• Note: In the code if you observe display method is called two times.
Display method will work according to the number of parameters
and type of parameters.
31. Polymorphism in C#
• When and why to use method overloading
• Use method overloading in situation where you want a class to be able to do something, but there
is more than one possibility for what information is supplied to the method that carries out the
task.
• You should consider overloading a method when you for some reason need a couple of methods
that take different parameters, but conceptually do the same thing.
• Method Overloading showing many forms.
• using System;
• namespace method_overloading_polymorphism
• {
• class Program
• {
• public class Shape
• {
• public void Area(float r)
• {
• float a = (float)3.14 * r;
• // here we have used funtion overload with 1 parameter.
• Console.WriteLine("Area of a circle: {0}",a);
• }
32. Polymorphism in C#
• public void Area(float l, float b)
• {
• float x = (float)l* b;
• // here we have used funtion overload with 2 parameters.
• Console.WriteLine("Area of a rectangle: {0}",x);
• }
• public void Area(float a, float b, float c)
• {
• float s = (float)(a*b*c)/2;
• // here we have used funtion overload with 3 parameters.
• Console.WriteLine("Area of a circle: {0}", s);
• }
• }
33. Polymorphism in C#
• static void Main(string[] args)
• {
• Shape ob = new Shape();
• ob.Area(2.0f);
• ob.Area(20.0f,30.0f);
• ob.Area(2.0f,3.0f,4.0f);
• Console.ReadLine();
• }
• }
• }
• Things to keep in mind while method overloading
• If you use overload for method, there are couple of restrictions that the compiler imposes.
• The rule is that overloads must be different in their signature, which means the name and the
number and type of parameters.
• There is no limit to how many overload of a method you can have. You simply declare them in a
class, just as if they were different methods that happened to have the same name.
34. Method overriding
• class BaseClass
{
public virtual string YourCity()
{
return "New York";
}
}
class DerivedClass : BaseClass
{
public override string YourCity()
{
return "London";
}
}
class Program
{
static void Main(string[] args)
{
DerivedClass obj = new DerivedClass();
string city = obj.YourCity();
Console.WriteLine(city);
Console.Read();
}
} }
•