Uploaded by Engr Muhammad Nadeem

C Sharp Basic

advertisement
The following are the key points of OOP languages:
Classes
Objects
Methods
abstraction
Encapsulation
Inheritance
Polymorphism
And so on.
For example:
C++, Java, C#, F#, VB.net .and so on.







Following is the detailed description of various data members which we used in above c# class
example.
What Inheritance is
Acquiring (taking) the properties of one class into another class is called inheritance.
Inheritance provides reusability by allowing us to extend an existing class.
The reason behind OOP programming is to promote the reusability of code and to
reduce complexity in code and it is possible by using inheritance.
The following are the types of inheritance in C#.
The inheritance concept is based on a base class and derived class. Let us see the
definition of a base and derived class.


Base class - is the class from which features are to be inherited into another
class.
Derived class - it is the class in which the base class features are inherited.
Single inheritance
It is the type of inheritance in which there is one base class and one derived class.
For example,
1. public class Accountcreditinfo //base class
2. {
3.
public string Credit()
4.
{
5.
return "balance is credited";
6.
}
7. }
8. public class debitinfo : Accountcreditinfo //derived class
9. {
10.
public string debit()
11.
{
12.
Credit();
////derived class me
thod
13.
return "balance is debited";
14.
}
15.
}
In the preceding sample program Accountcreditinfo is the base class and debitinfo is
the derived class.
Hierarchical inheritance
This is the type of inheritance in which there are multiple classes derived from one base
class. This type of inheritance is used when there is a requirement of one class feature
that is needed in multiple classes.
For example,
1. class A //base class
2. {
3.
public string msg()
4.
{
5.
return "this is A class Method";
6.
}
7. }
8. class B : A
9. {
10.
public string info()
11.
{
12.
msg();
13.
return "this is B class Method";
14.
}
15.
class C : A
16.
{
17.
public string getinfo()
18.
{
19.
msg();
20.
21.
22.
23.
return "this is B class Method";
}
}
}
In the preceding program one base class is derived in many classes hence it is a called
a Hierarchical Inheritance.
Multilevel inheritance
When one class is derived from another derived class then this type of inheritance is
called multilevel inheritance.
For example,
1. public class Person
2. {
3.
public string persondet()
4.
{
5.
return "this is the person class";
6.
}
7. }
8. public class Bird : Person
9. {
10.
public string birddet()
11.
{
12.
persondet();
13.
return "this is the birddet Class";
14.
}
15.
}
16.
public class Animal : Bird
17.
18.
19.
20.
21.
22.
23.
24.
{
public string animaldet()
{
persondet();
birddet();
return "this is the Animal Class";
}
}
In the preceding program, each class is derived from one class that is derived from
another class hence this type of inheritance is called Multilevel Inheritance.
Multiple inheritance using Interfaces
C# does not support multiple inheritances of classes. To overcome this problem we can
use interfaces, we will see more about interfaces in my next article in detail.
For example,
1. public interface IA //ineterface 1
2. {
3.
string setImgs(string a);
4. }
5. public interface IB //Interface 2
6. {
7.
int getAmount(int Amt);
8. }
9. public class ICar : IA, IB //implementatin
10.
{
11.
public int getAmount(int Amt)
12.
{
13.
return 100;
14.
}
15.
public string setImgs(string a)
16.
{
17.
18.
19.
return "this is the car";
}
}
In the preceding program the ICar class inherits the features of the two interfaces
hence this type of inheritance is called Multiple Inheritance.
The following are some key points about inheritance:
1. C# does not support multiple inheritances of classes; the same thing can be
done using interfaces.
2. Private members are not accessed in a derived class when one class is derived
from another.
What is Method Overloading?
Method overloading allows programmers to use multiple methods with the same name.
The methods are differentiated with their number and type of method arguments.
Method overloading is an example of the polymorphism feature of an object oriented
programming language.
Method overloading can be achieved by the following:



By changing number of parameters in a method
By changing the order of parameters in a method
By using different data types for parameters
Here is an example of method overloading.
1. public class Methodoveloading
2. {
3.
public int add(int a, int b) //two int type Parameters metho
d
4.
{
5.
return a + b;
6.
7.
}
8.
public int add(int a, int b,int c) //three int type Paramete
rs with same method same as above
9.
{
10.
return a + b+c;
11.
12.
}
13.
public float add(float a, float b,float c,float d) //fo
ur float type Parameters with same method same as above two metho
d
14.
15.
16.
17.
18.
{
return a + b+c+d;
}
}
In the above example, there are three methods with the same names but each method
differs in number of parameters and also types of parameters. This method is called
method overloading. One of the common example of method overloading is formatting
a string using the Format method. The string can be formatted using various input
types such as int, double, numbers, chars, and other strings.
FAQ of Method Overloading
Question: Can you overload a method based on a different return type?
Answer: No. Compiler does not allow just return type to seperate one method from
other with same name.
What is Method overriding?
Method overriding in C# allows programmers to create base classes that allows its
inherited classes to override same name methods when implementing in their class for
different purpose. This method is also used to enforce some must implement features
in derived classes.
Important points:


Method overriding is only possible in derived classes, not within the same class
where the method is declared.
Base class must use the virtual or abstract keywords to declare a method. Then
only can a method be overridden
Here is an example of method overriding.
1. public class Account
2. {
3.
public virtual int balance()
4.
{
5.
return 10;
6.
}
7. }
8. public class Amount:Account
9. {
10.
11.
public override int balance()
12.
{
13.
return 500;
14.
}
15.
}
In the above program, the result of the balance method can be 10 or 500.
The above code declares two classes, Account and Amount. The Amount class is
inherited from the Account class. Method balance is overridden in the Amount class.
The value of the balance method will be decided based on the caller program and its
use of base class or derived class.
What polymorphism is?
Polymorphism means one thing having many (poly) forms. Suppose the example shown
in the following diagram:
In the preceding example a vehicle is something that has various forms; two-wheeler,
three-wheeler and four-wheeler and so on. So how to differentiate each form in the
preceding example using wheels (parameters)? Let us see more about polymorphism,
There are two types of polymorphism; they are:
Compile time polymorphism
Compile time polymorphism is done at compile time. The following are examples of
compile time polymorphism.


Method overloading
Operator overloading
Method overloading
Creating multiple methods in a class with the same name but different parameters and
types is called method overloading.
Method overloading can be done in any of the following ways:



By changing the number of parameters used.
By changing the order of parameters.
By using different data types for the parameters.
For example:
1. namespace BAL
2. {
3.
public class Methodoveloading
4.
{
5.
public int add(int a, int b) //Method 1
6.
{
7.
return a + b;
8.
9.
}
10.
public int add(int a, int b, int c) //Method 2
11.
{
12.
return a + b + c;
13.
14.
}
15.
public float add(float a, float b, float c, float d)
//Method 3
16.
{
17.
return a + b + c + d;
18.
19.
}
20.
}
21.
}
In the preceding method there are three methods with the same name but different
parameter type. This is called method overloading. In my next article we will see the
program method of overloading in details.
Run time polymorphism
Run time polymorphism happens at run time, in other words values are ed at runtime to
the method. Runtime polymorphism can be done using method overriding.
Method overriding
Creating the method in a derived class with the same name, same parameters
and same return type as in the base class is called method overriding.


Method overriding is only possible in a derived class, not within the same class
where the method is declared.
Only those methods overriden in the derived class declared in the base class
using the virtual keyword or abstract keyword.
For example:
1. namespace BAL
2. {
3.
public class methodoverriding
4.
{
5.
public virtual int balance()
6.
{
7.
return 10;
8.
}
9.
}
10.
public class Amount : methodoverriding
11.
{
12.
13.
public override int balance()
14.
{
15.
return 500;
16.
}
17.
}
18.
}
Output
10 and 500
In the preceding program we declare the Virtual method that returns 10 and the same
method we are using in the class Amount using the override keyword that at runtime
returns 500 without changing the values of the method, even the names are the same
sothe example above shows runtime polymorphism. In my next article we will see in
details a program with runtime polymorphism.
Difference between method overloading and method overriding
Method overloading
Creating multiple methods in a class with the same name but different parameters and
types is called method overloading.
Method overriding
Creating the method in a derived class with the same name, the same parameters
and the same return type as in a base class is called method overriding.
Difference between virtual method and abstract method
Introduction
In this article we will understand types of classes in C#. There are four different types
of classes available in C#. They are as follows:
1.
2.
3.
4.
Static class
Abstract class
Partial class
Sealed class
Static class
A class with static keyword that contains only static members is defined as static class.
A static class cannot be instantiated.
Characteristics of static class
1. Static class cannot instantiated using a new keyword.
2. Static items can only access other static items. For example, a static class can
only contain static members, e.g. variable, methods etc.
3. A static method can only contain static variables and can only access other static
items.
4. Static items share the resources between multiple users.
5. Static cannot be used with indexers, destructors or types other than classes.
6. A static constructor in a non-static class runs only once when the class is
instantiated for the first time.
7. A static constructor in a static class runs only once when any of its static
members accessed for the first time.
8. Static members are allocated in a high frequency heap area of the memory.
Example
1. using System;
2.
3. namespace StaticClass_Demo
4. {
5.
public static class HeightConvertor
6.
{
7.
public static double InchsToCentimeters(string HeightInIn
chs)
8.
{
9.
double inchs = Double.Parse(HeightInInchs);
10.
double Centimeters = (inchs* 2.54);
11.
return Centimeters;
12.
}
13.
14.
public static double CentimetesToInchs(string Height
InCentimeters)
15.
{
16.
double centimeters = Double.Parse(HeightInCentim
eters);
17.
double Inchs = (centimeters / 2.54);
18.
return Inchs;
19.
}
20.
}
21.
}
1. using System;
2.
3. namespace StaticClass_Demo
4. {
5.
class Program
6.
7.
8.
9.
{
static void Main(string[] args)
{
Console.WriteLine("Please select the convertor direct
ion");
10.
Console.WriteLine("1. From Inchs to Centimeters.
");
11.
Console.WriteLine("2. From Centimeters to Inchs.
");
12.
13.
string selection = Console.ReadLine();
14.
double C, I = 0;
15.
16.
switch (selection)
17.
{
18.
case "1":
19.
Console.Write("Please enter the height i
n inchs: ");
20.
C = HeightConvertor.InchsToCentimeters(C
onsole.ReadLine());
21.
Console.WriteLine("Hieght in centimeters
: {0:F2}", C);
22.
break;
23.
24.
case "2":
25.
Console.Write("Please enter the Height i
n centimeters: ");
26.
I = HeightConvertor.CentimetesToInchs(Co
nsole.ReadLine());
27.
Console.WriteLine("Height in Inchs: {0:F
2}", I);
28.
break;
29.
30.
default:
31.
Console.WriteLine("Please select a conve
rtor.");
32.
break;
33.
}
34.
35.
Console.WriteLine("Press any key to exit.");
36.
Console.ReadLine();
37.
}
38.
}
39.
}
Output
Abstract class
A class with abstract modifier indicate that class is abstract class. An abstract class
cannot be instantiated. The purpose of an abstract class is to provide a common
definition of a base class that multiple derived classes can share.
Characteristic of Abstract class
1. An abstract class cannot be instantiated.
2. An abstract class may contain abstract methods and accessors.
3. It is not possible to modify an abstract class with the sealed modifier because
the two modifiers have opposite meanings. The sealed modifier prevents a class
from being inherited and the abstract modifier requires a class to be inherited.
4. A non-abstract class derived from an abstract class must include actual
implementations of all inherited abstract methods and accessors.
Example
1. using System;
2.
3. namespace AbstractClass_demo
4. {
5.
public abstract class Customer
6.
{
7.
private string _firstName;
8.
private string _lastName;
9.
10.
public string FirstName
11.
{
12.
get
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
{
return _firstName;
}
set
{
_firstName = value;
}
}
public string LastName
{
get
{
return _lastName;
}
set
{
_lastName = value;
}
}
public abstract void FullName();
}
}
1. using AbstractClass_Demo;
2. using System;
3.
4. namespace AbstractClass_Demo
5. {
6.
class Program: Customer
7.
{
8.
static void Main(string[] args)
9.
{
10.
Program p = new Program();
11.
p.FirstName = "Farhan";
12.
p.LastName = "Ahmed";
13.
p.FullName();
14.
Console.ReadLine();
15.
16.
}
17.
public override void FullName()
18.
{
19.
LastName);
20.
21.
}
22.
}
Console.WriteLine("Full Name:"+FirstName + " " +
}
Output
Partial class
The partial keyword indicates that other parts of the class, struct, or interface can be
defined in the namespace. All the parts must use the partial keyword. All the parts must
be available at compile time to form the final type. All the parts must have the same
accessibility, such as public, private, and so on.
Characteristic of Partial class
1. All the partial class definitions must be in the same assembly and namespace.
2. All the parts must have the same accessibility like public or private, etc.
3. If any part is declared abstract, sealed or base type then the whole class is
declared of the same type.
4. Different parts can have different base types and so the final class will inherit all
the base types.
5. The Partial modifier can only appear immediately before the keywords class,
struct, or interface.
6. Nested partial types are allowed.
Example
1. using System;
2.
3. namespace PartialClass_Demo
4. {
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
public partial class PartialClass
{
private string _firstName;
private string _lastName;
public string FirstName
{
get
{
return _firstName;
}
set
{
_firstName = value;
}
}
public string LastName
{
get
{
return _lastName;
}
set
{
_lastName = value;
}
}
}
}
1. using System;
2.
3. namespace PartialClass_Demo
4. {
5.
public partial class PartialClass
6.
{
7.
public void FullName()
8.
{
9.
Console.WriteLine("Full Name:"+FirstName+" "+LastName
);
10.
}
11.
}
12.
}
1. using System;
2.
3. namespace PartialClass_Demo
4. {
5.
class Program
6.
{
7.
static void Main(string[] args)
8.
{
9.
PartialClass partial = new PartialClass();
10.
partial.FirstName = "Farhan";
11.
partial.LastName = "Ahmed";
12.
partial.FullName();
13.
14.
Console.ReadLine();
15.
}
16.
}
17.
}
Output
Sealed class
A class with sealed keyword indicates that class is sealed to prevent inheritance. Sealed
class cannot inheritance.
1.
2.
3.
4.
5.
6.
7.
using
using
using
using
using
System;
System.Collections.Generic;
System.Linq;
System.Text;
System.Threading.Tasks;
namespace SealedClass_Demo
8. {
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
public sealed class Employee
{
string firstName;
string lastName;
}
class Program:Employee
{
static void Main(string[] args)
{
}
}
}
Inheritance
Inheritance means it’s a kind of relation between two classes like parent and child. In
inheritance child class will acquire all properties from parent class like methods, events,
nested types of parent class, operators and fields.
Example of using Inheritance
Following is the simple example of defining inheritance in classes.
// Parent Class
class parent {
// your code
};
// Child Class
class child : parent {
// child class will inherit all properties from parent class
}
Instantiation
Instantiation means defining or creating new object for class to access all properties like
methods, operators, fields, etc. from class.
Example if Instantiation
Following is the example of defining instantiation in application.
class sampleclass {
// your code
}
class Program
{
static void Main()
{
// Instantiating sampleclass
sampleclass sobj = new sampleclass();
}
}
If you observe above syntax we created new object by instantiating sampleclass class. By
using new object sobj we can access all the methods and properties
from sampleclass class.
Download