Opps Concepts
·
Class
·
Class Types
1.
Static Class
2.
Abstract Class
3.
Sealed Class
4.
Partial Class
5.
Concrete Class/Non Abstract Class
6. Singleton Class/Non-Static
·
Classs Reference Variable
·
Fields And Properties
·
Methods
·
Method Types
7. Static Method
8. Abstract Method
9. Virtual Method/Pure Virtual Method
10. Partial Method
11. Annonymous Method
12. Extention Method
13. Concrete Method/Non Static Method
14. Sealed Method
·
Method Parameters
15. ValueType
16. RefType
17. ParamsArray
·
Local Variable
·
Object
·
Object Intializer
·
Constructor
·
Constructor overloading
·
Constructor Types
·
Default
·
Private
·
Copy
·
Parameterize
·
Static
·
Encapsulation
·
Access Modifier
·
Private
·
Public
·
Protected
·
Internal
·
Internal Protected
·
Inheritance
·
Single
·
Multilevel
·
Multiple Interface
Inheritance
·
Hybrid
·
Hirarchical
·
Polymorphism
·
Function Overloading
·
Function Overriding
·
Function Hidding
·
Virtual And Override Keyword
·
Virtual Method
·
Abstraction
·
Abstract Class
·
Abstract Method
·
Abstract Keyword
·
Interface
·
Interface Implementation
·
Default Implementation
·
Explicit Implementation
·
Interface Types
·
Non Generic Interface
·
Generic Interface
OPPs:- Object-Oriented
Programming System (OOPs) is a programming concept that works on the principles
of abstraction, encapsulation, inheritance, and polymorphism.
Object-oriented programming is about creating objects
that contain both data and methods.Classes and objects are the two main aspects
of object-oriented programming.
For example:- Everything in C# is associated with
classes and objects, along with its attributes and methods. in real life, a car is an object. The car has
attributes, such as weight and color, and methods, such as drive and brake.
A Class is like an object constructor, or a
"blueprint" for creating objects.
When a variable is declared directly in a class,
it is often referred to as a field (or attribute) and that you can access them
by creating an object of the class, and by using the dot syntax (.).
class Car
{
string color = "red";
int maxSpeed = 200;
static void
Main(string[]
args)
{
Car myObj = new Car();
Console.WriteLine(myObj.color);
Console.WriteLine(myObj.maxSpeed);
}
}
#Pillars of Object Oriented Programming
·
Encapsulation
·
Inheritance
·
Polypmorphism
·
Abstraction
Class:- A class is a data
structure that may contain data members (constants and fields), function
members (methods, properties, events, indexers, operators, instance
constructors, destructors and static constructors), and nested types.
·
Class types support inheritance.
·
Class are reference types.
·
The Default accessibility of class is internal we
can make it only public and the class member default accessility is private(it
is not fixed).we can make public,protected and internal.
·
Class describe all the attributes and behaviour
of a method.
# In Object oriented
programming Class is user defined data type which holds its own data members
and member functions that can be access
and used by creating the instance of that class.
# Class is user
defined type.
# A class is an
encapsulation of properties and methods that are used to represent a real-time
entity.
# A Class consists
of data and behavior. Class data is represented by it's fields and behavior is
represented its methods.
Why used Classes
We have simple data
types like int, float, double, etc. If you want to create complex custom types,
then we can make use of classes.
Example:-
class Customer
{
//Fields represent the class data.
string
_firstName;
string
_lastName;
//Constructor used to initialez class fields.Constructor
can't have return type.
public
Customer(string FirstName,string
LastName)
{
_firstName = FirstName;
_lastName = LastName;
//OR
this._firstName
= FirstName;
this._lastName
= LastName;
//for
better readability use this keyword.athis keyword represent the instance of
this class.
}
//Method represent the behavior of class.
public void
PrintFullName()
{
Console.WriteLine("Full
Name={0}", this._firstName,
this._lastName);
}
}
class Program
{
static void Main(string[] args)
{
Customer C1 = new Customer("SunFarma","Biotech");
Customer C2 = new Customer("Hair", "Technology");
C1.PrintFullName();
C2.PrintFullName();
C1,C2 is the instance/object of the
class.A Constructor called automatically
when the instance of the class is created.
}
}
#Static and Instance Member of Class
·
When a class member includes a static modifier
,the member is called as static member.When no static modifier is present the
member is called as non static member or instance member.
·
Static member are invoked using class name ,
where as instance member are invoked using instances(object) of the class.
·
An Instance member belongs to specific
instance(object) of a class. If i create 3 objects of a class, i will have 3
sets of instance members in the memory, where as there will ever be only one
copy of a static member, no matter how many instances of classs is created.
Classs
members: fields,methods,properties,events,indexer,constructors.
1.Instance
Member
class Circle
{
float _PI = 3.141f;
int _Radius;
public Circle(int
Radius)
{
this._Radius = Radius;
}
public float
CalculateArea()
{
return this._PI * this._Radius
* this._Radius;
}
}
class Program
{
public static void Main()
{
Circle C1 = new Circle(5);
float Area1 = C1.CalculateArea();
Console.WriteLine("Area={0}",Area1);
Circle C2 = new Circle(5);
float Area2 = C2.CalculateArea();
Console.WriteLine("Area={0}", Area2);
}
}
2.Static Member
class Circle
{
static float
_PI; // use static modifier if the value of the
class member is not changed per object.
int _Radius;
public Circle(int
Radius)
{
this._Radius = Radius;
}
static Circle()
{
//A Static Constructor must be parameterless.And does not have any access
modifier.
//Static Constructor does not need to be called.
//Static Constructor will be
invoked only once for all of instances of the class.
Circle._PI = 3.141f;
//this._PI is wrong here because this represent instance member.
//this._Radius is wrong here because this keyword is not valid with static
property,static method.
}
public float
CalculateArea()
{
return Circle._PI * this._Radius * this._Radius;
}
}
class Program
{
public static void Main()
{
Circle C1 = new Circle(5);
float Area1 = C1.CalculateArea();
Console.WriteLine("Area={0}",Area1);
Circle C2 = new Circle(6);
float Area2 = C2.CalculateArea();
Console.WriteLine("Area={0}", Area2);
}
}
#Classes Types
Concrete class :-
·
A concrete class is a class that has an
implementation for all of its methods.
Static Class:-
·
Is sealed/Not Inherited
·
Cannot be instantiated.//use class name to call
member.
·
Use 'static' Keyword
·
Contains only static members.
·
Cannot contain Instance Constructors have static
constructor.
Sealed Class :-
·
Is sealed/Not Inherited.
·
Can be instantiated.
·
Use 'sealed' Keyword.
Abstract Class :-
·
Is not sealed/Inherited.
·
Cannot be instantiated.
·
Use 'abstract' Keyword.
·
Contains abstract and non abstract method.
Non-Static/Singleton
Class:-
·
Non-static class allows only one instance of
itself to be created.
·
Use Private Constructor.
Partial Class:-
·
A partial class is a special feature of C#. It
provides a special ability to implement the functionality of a single class
into multiple files and all these files are combined into a single class file
when the application is compiled. A partial class is created by using a partial
keyword.
Object:- In object oriented
programming object is an instance of the class that has
attribute(property), behaviour and
identity.Attribute and behaviour of an object are defined by the class
defination.
An example of an
object is a car. A car has attributes (e.g., colour, size, weight, fuel
capacity, number of passengers, etc.
). A car has
behaviour represented by its methods (e.g., start engine, turn left/right, accelerate, stop, turn on wipers,
etc.).
A class is a special
kind of object that’s used as a template for creating instances of itself.
Think of it like a cookie cutter that
produces cookies (or objects).
It is useful to
think of an object's identity as the place where its value is stored in memory
or user defined names of objects.
# The Reference type
variable:- The Reference type variable is such type of variable in C# that holds the
reference of memory address instead of value. class, interface, delegate, array
are the reference type. When you create an object of the particular class with
new keyword, space is created in the managed heap that holds the reference of
classes.
class Program
{
public static void Main()
{
Program1 p = new Program();
//Here p is a Class(Program) reference variable.
}
}
Object Initializer :- C# 3.0 (.NET 3.5)
introduced Object Initializer Syntax, a new way to initialize an object of a
class or collection. Object initializers allow you to assign values to the
fields or properties at the time of creating. an object without invoking a
constructor.
public class Student
{
public int
StudentID { get; set; }
public string
StudentName { get; set; }
public int Age { get; set; }
public string Address
{ get; set; }
}
class Program
{
static void Main(string[] args)
{
Object
Initializer Syntax:-
Student std = new Student()
{
StudentID = 1,
StudentName = "Bill",
Age = 20,
Address = "New
York"
};
var student1 = new Student() { StudentID = 1,
StudentName = "John" };
var student2 = new Student() { StudentID = 2,
StudentName = "Steve" };
var student3 = new Student() { StudentID = 3,
StudentName = "Bill" };
var student4 = new Student() { StudentID = 3,
StudentName = "Bill" };
var student5 = new Student() { StudentID = 5,
StudentName = "Ron" };
Collection
initializer Syntax:-
List<Student>
studentList = new List<Student>() {
new Student() {
StudentID = 1, StudentName = "John"} ,
new Student() {
StudentID = 2, StudentName = "Steve"} ,
new Student() {
StudentID = 3, StudentName = "Bill"} ,
new Student() {
StudentID = 3, StudentName = "Bill"} ,
new Student() {
StudentID = 4, StudentName = "Ram" } ,
new Student() {
StudentID = 5, StudentName = "Ron" }
};
}
}
https://www.tutorialsteacher.com/csharp/csharp-object-initializer
Method :- A method is a block of code which only runs when
it is called. You can pass data, known as parameters, into a method. Methods
are used to perform certain actions, and they are also known as functions.Why
use methods? To reuse code: define the code once, and use it many times.
# Method is a code block that contain a series of statement to perform a
specific task.
#Function are called independently while method are called by using
instance(object).
#Function are used in structure programming while methods use in object
oriented programming.
#Method and Function terms are used interchangebly.
Syntax:-
[attributes]
access-modifiers
return-type method-name(parameters)
{
method-body
}
# Just like with
fields, you can access methods with the dot syntax. However, note that the
method must be public. And remember that we use the name of the method followed
by two parantheses () and a semicolon ; to call (execute) the method:
class Car
{
string color; // field
int maxSpeed; // field
public void
fullThrottle() // method
{
Console.WriteLine("The car is going as fast as it can!");
}
static void
Main(string[]
args)
{
Car myObj = new Car();
myObj.fullThrottle(); // Call the method
}
}
Why
did we declare the method as public, and not static?
The reason is
simple: a static method can be accessed without creating an object of the
class, while public methods can only be accessed by objects.
#Instance method vs
static method
#argument vs
parameter
·
parameters are the names listed in the function's
definition.
·
arguments are the real values passed to the
function.
·
parameters are initialized to the values of the
arguments supplied.
#The 4
types of method parameters
·
Value Parameters:- Create
the copy of the parameters,so modifications does not affect each other.
·
Reference Parameters(ref keyword):- The ref
parameter keyword on a method parameter refer to the same variable that was
passed into the method. Any change made into the into the method reflected into
the that variable when control passed
back to calling method.
·
Out Parameters(out keyword):- Use
when you want to a method return multiple value.ref can also return multiple
value.
·
Parameter Arrays(params keyword):- The
params keyword lets you specify a method parameter that takes a variable number
of arguments.
#Optional Parameters
:- A parameter with a default value, is often known as an "optional
parameter".
#Named Parameters in C#
#Types of Method in C#
·
Pure Virtual Method
·
Virtual Method
·
Abstract Method
·
Concreat Method
·
Partial Method
·
Static Method
·
Sealed Method
Sealed methods:-A sealed class is a
class which cannot be a base class of another more derived class.
A sealed method in
an unsealed class is a method which cannot be overridden in a derived class of
this class.
To prevent being
overridden, use the sealed in C#. When you use sealed modifiers in C# on a
method, then the method loses its capabilities of overriding. The sealed method
should be part of a derived class and the method must be an overridden method.
public sealed override void getResult() {
}
Fields and
Property:- A field is a variable of any type that is declared directly in a class or
struct. Fields are members of their containing type.
#Why Properties:-Marking
the class field public and exposing to
the external world is bad idea, as you will not have control over what gets
assigned and returned.This is the violation all
business rules.
class Student
{
public int _id;
public string _name;
public int _passMark;
}
class Program
{
public static void Main()
{
Student C1 = new Student();
C1._id = -101;
C1._name = null;
C1._passMark = 0;
Console.WriteLine("Student Id={0} && Name={1} && PassMark={2}",C1._id,C1._name,C1._passMark);
}
}
# Programming
languages that does not have properties use getter and setter methods to
encapsulates and protect fields.
class Student
{
private int _id;
public string _name;
public int _passMark;
public void SetId(int id)
{
if(id<=0)
{
throw new Exception("Student id
should be greater than 0");
}
this._id = id;
}
public int GetId()
{
return _id;
}
}
class Program
{
public static void Main()
{
Student C1 = new Student();
C1.SetId(101);
Console.WriteLine("Student Id={0}",C1.GetId());
}
}
# Properties are the special
type of class members that provides a flexible mechanism to read, write, or
change the class variable's value(fields) without affecting the external way of
accessing it in our applications.
#Properties expose
fields.
#Fields should
(almost always) be kept private to a class and accessed via get and set
properties. Properties provide a level of abstraction allowing you to change
the fields while not affecting the external way they are accessed by the things
that use your class.
Example:-
class Student
{
//Class Fields
private int _id;
public string _name;
public int _passMark;
//Class Properties
public int Id
{
set
{
if (value <= 0)
{
throw new Exception("Student Id
should be greater than 0");
}
this._id = value;
}
get
{
return
this._id;
}
}
//Auto Implemented properties.
public string Email { get; set }
}
class Program
{
public static void Main()
{
Student C1 = new Student();
C1.Id = 101;
Console.WriteLine("Student Id={0}",C1.Id);
}
}
·
Read and Write Properties: - When property
contains both get and set methods.
·
Read-Only Properties:- When property
contains only get method.
·
Write Only Properties:- When property contains only set method.
·
Auto Implemented Properties:- If there is no
additional logic in the property accessors,then we can make use of auto
implemented properties introduced in C#3.0.These reduce the ammount of code
that we have to write.
#When we use Auto Implemented Properties,the
compiler creates a a private , annonymous field that can be access through the
property's get and set accessors.
Properties and
fields provide access to the data contained in an object.Both fields and properties
are typed, so you can store information in them as string values, as int
values, and so on. However, properties differ from fields in that they don’t
provide direct access to data.
Objects can shield
users from the nitty-gritty details of their data, which needn’t be represented
on a one-to-one basis in the properties that exist. If you used a field for the
number of sugars in a CupOfCoffee instance, then users could place whatever
values they liked in the field, limited only by the
limits of the type
used to store this information. If, for example, you used an int to store this
data, then users could use any value between −2147483648 and 2147483647, as
shown in Chapter 3. Obviously, not all values make sense, particularly the
negative ones, and some of the large positive amounts might require an
inordinately large cup. If you use a property for this information, then you
could limit this value to, say, a number between 0 and 2. In general, it is
better to provide properties rather than fields for state access because you
have more control over various behaviors. This choice doesn’t affect code that
uses object instances because the syntax for using properties and fields is the
same.Read/write access to properties may also be clearly defined by an object.
Constructor:- Constructor is a
special method of class that is invoked automatically when the instance of class is created and initialized
all the data memeber of class.constructer has the same name as class.The main use of constructors is
to initialize private fields of the class while creating an instance for the class.
·
Constructor of a class must have the same name as
the class name in which it resides.
·
A constructor can not be abstract, final/sealed
Synchronized.
·
A constructor doesn’t have any return type, not
even void.
·
A class can have any number of constructors.
·
Access modifiers can be used in constructor
declaration to control its access i.e which other class can call the
constructor.
·
With no public constructors, it will not be
possible to create an instance of your class.
#Constuctor
Overloading:-
1.Defuault:- When you have not
created a constructor in the class, the compiler will automatically create a default constructor of the class.
The default constructor initializes all numeric fields in the class to zero and all string and object
fields to null Refrence
Implicit/Explicit
#Instance
constructors are used to create and initialize any instance member variables
when you use the new expression to create an object of a class.
#All value types
implicitly declare a public parameterless instance constructor called the
default constructor. The default constructor returns a zero-initialized
instance known as the default value for the value type:
# Default access
modifier for Default constructor is Public.but if u create a constructor of
your own then the default access modifer is private.
2.Parameterize:A constructor with
at least one parameter is called a parametrized constructor
3.Copy:This constructor
will creates an object by copying variables from another object. Its main use
is to initialize a new instance to the values of an existing instance.
A copy constructor
creates a new object by copying variables from an existing object of the same
type.C# does not provide a copy constructor, so if you want one you must
provide it yourself.
4.Static:-
# A static
constructor is used to initialize static fields of the class or to perform an
particullar action that needs to be executed only once.
# When a constructor
is created using a static keyword, it will be invoked only once for all of
instances of the class and it is invoked before the creation of the first
instance of the class.
# A static
constructor runs before an instance constructor.
# If you don't
provide a static constructor to initialize static fields, all static fields are
initialized to their default value.
# Access modifier
are not allowed with static constructor.
# A static
constructor cannot be a parameterized constructor or we can say
Static constructors
are parameterless.
# Within a class,
you can create only one static constructor.
A class can have a
single static constructor, which must have no access modifiers and cannot have
any parameters. A static constructor can never be called directly; instead, it
is executed when one of the following occurs:
➤ An instance of the class containing the static
constructor is created.
➤ A static member of the class containing the
static constructor is accessed.
In both cases, the
static constructor is called first, before the class is instantiated or static
members accessed. No matter how many instances of a class are created, its
static constructor will only be called once.
all nonstatic
constructors are also known as instance constructors.
If your class
declares a static constructor, you will be guaranteed that the static
constructor will run before any instance of your class is created
class Circle
{
static float
_PI;
int _Radius;
public Circle(int
Radius)
{
this._Radius = Radius;
}
static Circle()
{
Circle._PI = 3.141f;
}
public float
CalculateArea()
{
return Circle._PI * this._Radius * this._Radius;
}
}
class Program
{
public static void Main()
{
Circle C1 = new Circle(5);
float Area1 = C1.CalculateArea();
Console.WriteLine("Area={0}",Area1);
Circle C2 = new Circle(6);
float Area2 = C2.CalculateArea();
Console.WriteLine("Area={0}", Area2);
}
}
·
A Static Constructor must be
parameterless.And does not have any access modifier.
·
Static Constructor does not need to
be called.
·
Static Constructor will be invoked only once for all of instances
of the class.
·
What is static constructor.
When a constructor is created using a static
keyword then it is called static constructor.
·
use of static constructor.
A static constructor is used to initialize static
fields of the class and to write the code that needs to be executed only once.
·
can we have access modifier in static constructor
No
·
can we pass parameters in static constructor.
No
·
how to call static constructor or when static
constructor is called.
·
how many time we can call static constructor.
Only Once.
5.Private:- Private
constructors are used to prevent creating instances of a class .When a
constructor is created with a private specifier, it is not possible for other
classes to derive from this class, neither is it possible to create an instance
of this class. They are usually used in classes that contain static members
only.
Some key points of a
private constructor are:
1.One use of a
private constructor is when we have only static members.
2.It provides an
implementation of a singleton class pattern
3.Once we provide a
constructor that is either private or public or any, the compiler will not add
the parameter-less public constructor to the class.
or we can say we can
not put private and public constructor at once in a class.
Constructor Channing:- Constructor Chaining is an approach where a
constructor calls another constructor in the same or base class.we can achieve
using this and base keyword.
https://www.codeproject.com/Articles/271582/Constructor-Chaining-in-Csharp-2
Note:-Second link also important
Constructor chaining is strongly coupled with
constructor overloading.
·
Static constructors initialize only static
members of the type.
·
Private constructors are special constructors
used only in classes that contain only static members.
·
Copy constructors take as an argument an instance
of the same class.
·
Instance constructors are the most commonly used.
They initialize the instance member variables when you use the new expression.
1.Encapsulation:- Encapsulation means bind the data members
(Variable) and member functions (Method) in a single unit for prevent
unauthorized access of them.
Example: Classes
We can achieve encapsulation by Access modifier in C#
Note:- Elements(class,interface,struct,enum) defined in
a namespace cannot be explicitly declared as private, protected, or protected
internal or we can say default accessbility of class ,interface,struct,enum are
internal and change to only public.
·
Public:- The type or member can be accessed by any other code in the same assembly
or another assembly that references it.
·
Private:- Private member are accessible only
within their containing type.
·
Protected:-Protected Members are accessible, with in the containing type and to the
types that derive from the containing type.
·
Internal:- The type with internal access modifier is accessible anywhere within their
containing assembly.
·
Protected Internal:- Protected Internal members can be accessed by any code in the assembly in
which it is declared, or from within a derived class in another assembly.
Note:- During Inheritance BaseClass can not less accessable compare to derived
otherwise it would be compile time error.
class BaseClass
{
}
public class DerivedClass:BaseClass
{
}
it gives compile time error. Inconsistent
accessabiltiy
2.Inheritance:- Inheritance means reuse the code functionality and speed up the
implementation time.Types of Inheritance
in C#:
# A Parent Class refrence variable can
point to a Derived class object.
ParentClass r2 = new DerivedClass();
// Here r2 is parent
class refrence variable.
// new
DerivedClass() is a derived class object.
# Sealed Classses:- Sealed classes are
used to restrict the users from inheriting the class. A class can be sealed by
using the sealed keyword. The keyword tells the compiler that the class is
sealed, and therefore, cannot be extended. No class can be derived from a
sealed class.
# A method can also
be sealed, and in that case, the method cannot be overridden. However, a method
can be sealed in the classes in which they have been inherited. If you want to
declare a method as sealed, then it has to be declared as virtual in its base
class.
# Sealed classes are
used best when you have a class with static members.
# Marking a class as
Sealed prevents tampering of important classes that can compromise security, or
affect performance.
# Many times,
sealing a class also makes sense when one is designing a utility class with
fixed behaviour, which we don't want to change.
# For example,
System namespace in C# provides many classes which are sealed, such as String.
If not sealed, it would be possible to extend its functionality, which might be
undesirable, as it's a fundamental type with given functionality.
# Sometimes, when
you are building class hierarchies, you might want to cap off a certain branch
in the inheritance chain, based on your domain model or business rules.
1.Single:A class inherited by single parent
class.
A
|
B
Example:-
public class Employee
{
public float
salary = 40000;
}
public class Programmer : Employee
{
public float
bonus = 10000;
}
class TestInheritance
{
public static void Main(string[] args)
{
Programmer p1 = new Programmer();
Console.WriteLine("Salary: " + p1.salary);
Console.WriteLine("Bonus: " + p1.bonus);
}
}
2.MultiLevel:- When one class inherits another
class which is further inherited by another class, it is known as multi level
inheritance in C#.
A
|
B
|
C
https://www.tutorialandexample.com/csharp-multilevel-inheritance/
3.Multiple Interface Inheritance:A Class
inherited by multiple parent class.
A B
C
4.Hirarchical:More than one class is inherited
from the base class in Hierarchical Inheritance.
A
B C D
E
Ex :-
public class Employee
{
public string
FirstName;
public string
LastName;
public void
PrintFullName()
{
Console.WriteLine(FirstName+" "+LastName);
}
}
public class FullTimeEmployee:Employee
{
public float
YearlySalary;
}
public class PartTimeEmployee:Employee
{
public float
HourlySalary;
}
public class Program
{
static void
Main(string[]
args)
{
FullTimeEmployee FT = new FullTimeEmployee();
FT.FirstName = "Mittal";
FT.LastName = "Kumar";
FT.PrintFullName();
}
}
5.Hybrid:Combination of Multiple and Hirarchical
Inheritance
A
B C
D
3.Polymorhpism:- Polymorphism provides the ability to a class to have multiple
implementations with the same name. It is one of the core principles of Object
Oriented Programming after encapsulation and inheritance.
There are two types of polymorphism in C#
1.Static / Compile Time Polymorphism:-It is also known as Early Binding. Method overloading is an example of
Static Polymorphism.It is also known as Compile Time Polymorphism because the
decision of which method is to be called is made at compile time.
Here C# compiler checks the number of parameters
passed and the type of parameter and make the decision of which method to call
and it throw an error if no matching method is found.
2.Dynamic / Runtime Polymorphism:- Dynamic / runtime polymorphism is also known as late binding. Here, the
method name and the method signature (number of parameters and parameter type
must be the same and may have a different implementation). Method overriding is
an example of dynamic polymorphism.
Here C# compiler would not be aware of the method
available for overriding the functionality, so the compiler does not throw an
error at compile time.
https://www.c-sharpcorner.com/UploadFile/ff2f08/understanding-polymorphism-in-C-Sharp/
# Method Overriding means creating more than function with same name and same in parameter but
in diffirent class one should be
baseclass and other should be derived class. We use virtual keyword in base class and override keyword
in derived class.
public class BaseClass
{
public virtual void Print()
{
Console.WriteLine("I am in
BaseClass");
}
}
public class DerivedClass : BaseClass
{
public override void Print()
{
Console.WriteLine("I am in
DerivedClass");
}
}
public class Program
{
static void Main(string[] args)
{
DerivedClass obj = new DerivedClass();
obj.Print();
}
}
#Method Overloading means create more than one function with same name and in same class but
diffirent number and type of parameters and a function also be overloaded with
different kind of parameters.Real world example of function overloading is
Calculator.
class FunctionOverloading
{
public static void Add(int fn, int ln) { }
public static void Add(float fn, float ln) { }
public static void Add(int fn, float ln) { }
public static void Add(int fn, int ln, int mn) { }
public static void Add(int fn, int ln, out int Sum)
{
Sum = fn + ln;
}
}
Note:- A method can not be overloaded just
based on return type or params keyword.
#Method Hiding C# also provides a concept to hide the methods of the base class in a
derived class, this concept is known as Method Hiding. It is also known as
Method Shadowing.
In method
hiding, we can hide the implementation of base class method from the derived class by using the new keyword. Or in other words, in method hiding,
you can redefine the base class method in the derived class by using the new
keyword.
class BaseClass
{
public void Print()
{
Console.WriteLine("I am in
BaseClass");
}
}
class DerivedClass : BaseClass
{
public new void Print()
{
Console.WriteLine("I am in
DerivedClass");
}
}
class Program
{
static void Main(string[] args)
{
DerivedClass obj = new DerivedClass();
obj.Print();
}
}
How to call a hidden method:-
·
By
using the base keyword.
·
By
casting the derived class type to base class type.
·
Instead
of using derived class reference variable we use the parent class reference
variable for calling the hidden method.
https://www.geeksforgeeks.org/method-hiding-in-c-sharp/
https://www.geeksforgeeks.org/difference-between-method-overriding-and-method-hiding-in-c-sharp/
Note:- If we have two
class one is BaseClass and Other is DerivedClass and we want to redefine the
implementation of BaseClass method in DerivedClass then we have two choices one
is Method Overriding and other is Method
Hiding.Method Overriding achieve by virtual and override keyword while Method
Hiding achieve by new keyword. In Method Overriding we just override the
existing BaseClass method in Derived Class and provide it to a new
implementation. In Method Hiding we Hide the Implementation of BaseClass method
in DerivedClass and create a new method with same name and provide a new
implementation to it.
4.Abstraction:- Data Abstraction means hide the complexity and showing the related functionality of the
system to the User.
Data abstraction is the process of hiding certain
details and showing only essential information to the user.Abstraction can
be achieved with either abstract classes or interfaces.
Example:Like we use many namespaces and package
in our application we just pass the reference of the them witout knowing the complexity behind
them. Abstract class use for acheive the abstraction.
# Abstract class:- When we create a class with abstract keyword it is known as
abstract class.we can not create the instance of abstract class.Abstract class
can have abstract and non abstract method.Abstract member must be implemented
by non-abstract classes that derive from the abstract class.
#Note:- We would create an abstract class , when
we want to move the common functionality of 2 or more related classes into a
base class and when we don't want that base class to be instantiated.
# A abstract class can have constructure :Yes
# Use of virtual method in asbtract class.
public abstract class Customer
{
public abstract void Print1();
public void
Print2()
{
Console.WriteLine("Print2 Method");
}
}
class Program:
Customer
{
public override void Print1()
{
Console.WriteLine("Print1 Method");
}
public static void Main()
{
Program p = new Program();
p.Print1();
p.Print2();
}
}
//Or we can do this
public abstract class Customer
{
public abstract void Print1();
public void
Print2()
{
Console.WriteLine("Print2 Method");
}
}
abstract class Program: Customer
{
public static void Main()
{
}
}
Properties of Abstract Class
·
we can not create the
instance of abstract class.
·
An abstract class can not be
static or sealed.
·
A abstract
class,class,interface can not be define as private because element define in a
namespace can not be explicitly(manually) declared private,protected,protected
internal these are by default internal and can be declared as public.
·
we can define static and
virtual method in abstract class but need to define body but we can not define
a abstract method as static because a static can not be abtract or
partial,override or virtual.
·
we can not define private
abstract method in abstract class.
·
Abstract class can inherit
another abstract class or normal class but can not implement interface and can
not inherit another static class.
·
Can we use virtual method in
abstract class?
Answer: Yes, We can have virtual method in an
Abstract class in C#. This is true that both virtual and abstract method allow
derived classes to override and implement it. But, difference is that an
abstract method forces derived classes to implement it whereas virtual method
is optional.
Example:
ActionResult
ActionFilterAttribute
Example:Animal
Class(Base Class)
SubClass:Dog
Class,Cat Class,Cow Class.
# Interface:- Interface is a
contract where we can defined only public abstract method and method must be
implement by a class that implement the interface.
# We create interface
using interface keyword. Just like classes interfaces also contains
properties,methods, delegates or events , but only declaration and no
implementations.
# Interface allow us
to to develope loosely-coupled application(System).
# Interface are very
useful for dependeny Injection.
# Interface make
unit testing and mocking easier.
An interface is a
collection of public instance (that is, nonstatic) methods and properties that
are grouped together to encapsulate specific functionality. After an interface
has been defined, you can implement it in a class. This means that the class
will then support all of the properties and members specified by the interface.
Interfaces cannot exist on their own. You can’t ‘‘instantiate an interface’’ as
you can a class.
interface ICustomer
{
Product product { get; set; } //Properties
void Print(); //Method
//int i; //Field Not
Allowed
}
interface IRegion:ICustomer
{
void DeliveryAttempt();
}
interface IProduct
{
void Details();
}
class Program
: IRegion,IProduct
{
public void
DeliveryAttempt()
{
throw new NotImplementedException();
}
public void
Print()
{
throw new NotImplementedException();
}
public void
Details()
{
throw new NotImplementedException();
}
public static void Main()
{
Program p = new Program();
p.DeliveryAttempt();
p.Print();
OR
IRegion r = new Program();
r.DeliveryAttempt();
r.Print();
// r is a interface reference variable
}
}
Note:-
·
Interface does not have fields so obiviously no
constructor.
·
By default interface are Internal by
accessabilty. Interface member can not have access modifier because by default
they are public.
·
We can not create the instance of Interface but an interface reference variable can point to a derived
class.
·
Interface method must be implemented by a Derived
Class.
·
We can declare only abstract method(only
declartion ,no defination) in interface.
·
We always use public modifier for implement
interface method in derivied class.
·
Interface slove the problem of multiple class
inheritance because a class can inherite multiple interface but can't inherit
multiple class.
·
An Interface can inherit only another Interface
not a class or abstract class.
#Default Interface
Implementation.
interface I1
{
void IneterfaceMethod();
}
interface I2
{
void IneterfaceMethod();
}
class Program
: I1,I2
{
//Default
Interface Implementation
public void
IneterfaceMethod()
{
Console.WriteLine("I1 Interface Method");
}
//Explicit
Interface Implementation
void I2.IneterfaceMethod()
{
Console.WriteLine("I2 Interface Method");
}
public static void Main()
{
Program p = new Program();
p.IneterfaceMethod();
((I2)p).IneterfaceMethod();
}
}
#Explicit Interface
Implementation.
How to implement two interface with same name
method in C#?
https://www.interviewsansar.com/how-to-implement-two-interfaces-having-same-method-in-csharp/
# Access modifier are not allowed on explicitly
implemented interface member.
# when a class explicitly implments an interface,
the interface member can no longer be accessed through class refrence
variable,but only through interface refrence variable.
interface I1
{
void IneterfaceMethod();
}
interface I2
{
void IneterfaceMethod();
}
class Program
: I1,I2
{
void I1.IneterfaceMethod()
{
Console.WriteLine("I1 Interface Method");
}
void I2.IneterfaceMethod()
{
Console.WriteLine("I2 Interface Method");
}
public static void Main()
{
Program p = new Program();
//Type
Caste
((I1)p).IneterfaceMethod();
((I2)p).IneterfaceMethod();
//Here I1,I2 are interface refrence variable.
//OR
I1 i1 = new Program();
I2 i2 = new Program();
i1.IneterfaceMethod();
i2.IneterfaceMethod();
}
}
# virtual and
abstract method can not be private.
# can not create an
instance of the abstract class and interface.
Difference
# Diff between
declaration,implementation, definition.
# Diff between
Constructor and Method
Constructor
Method
A constructor is
used to initialize an object. Method is used to expose the
behavior of an object.
The constructor must
not have a return type. Method
has or not have a return type.
Constructor must be
the same as the class
Method name may or may not be same as the class name
name
A constructor is invoked implicitly as well as ex Method is invoked only explicitly.
explicitly
# Diff between
Abstract Method and Virtual Method.
·
Abstract method have only defination and Virtual
mehod have defination and body in same class.
·
Abstract mehtod forece to derived for implement
itself but Virtual mehtod it is optional.
·
Abstract and Virtual Metohd can't be declared
private.
# Diff between Abstract Class and Interface.
https://www.codeproject.com/Articles/11155/Abstract-Class-versus-Interface
# Diff between
Virtual and Override keyword.
Virtual:- Virtual makes a base
class method ovveridable in derived class.The virtual keyword designates a
method that is overridden in derived classes.
Private virtual methods cannot be declared in the
C# language.
Override :- Override keyword modifies a virtual method of base
class in derived class.The override
keyword specifies that a method replaces its virtual base method. We use
override in derived classes to replace inherited methods.
# Diff between Constructor and Properties.
https://www.c-sharpcorner.com/forums/differences-between-constructors-and-properties
# Diff between Instance and Constructure.
# Diff between Instance and Object.
# Diff between method overloading and method
hiding.
1.Method Overriding is a technique that allows the
invoking of functions from another class (base class) in the derived class.
2.It only redefines the implementation of the
method.
1.In Method Hiding, you can hide the implementation
of the methods of a base class from the derived class using the new keyword. Or
in other words, in method hiding, you can redefine the method of the base class
in the derived class by using the new keyword.
2.In method hiding, you can completely redefine the method.
# Diff between
Sealed Classes and Static Classes.
Sealed Class | Static Class
-------------------------- |-------------------------
it can inherit From
other | it cannot inherit From other
classes but cannot
be | classes as well as cannot
be
inherited | inherited
A class can be
declared static, indicating that it contains only static members. It is not
possible to create instances of a static class using the new keyword. Static
classes are loaded automatically by the .NET Framework common language runtime
(CLR) when the program or namespace containing the class is loaded.
Sealed Class:- A
sealed class cannot be used as a base class. Sealed classes are primarily used
to prevent derivation. Because they can never be used as a base class, some
run-time optimizations can make calling sealed class members slightly faster.
# Diff between Abstract Class and Interface.
1.Abstract class can have implementation for some of its
members(methods),but the interface can't have implementation for any of its
members.
2.Abstract class have fields where as Interface can't have fields.
3.Abstract class can inherit from another abstract class or another
interface where as an interface can inherit from another interface only.
4.Abstract class members can have access modifiers where as interface
members can't have access modifiers.
# Diff between pure virtual method and abstract method.
# Constructor Types according to Access Modifier
·
Public
·
Private
·
Static
·
Base:Base keyword is used to
call the Base Class constructor.
·
Static
·
This
https://www.dotnetperls.com/constructor
# Abstract type and concrete type:In programming languages, an abstract type is a type in a nominative type
system that cannot be instantiated directly; a type that is not abstract –
which can be instantiated – is called a concrete type. Every instance of an
abstract type is an instance of some concrete subtype
Static vs Abstract Class:-
static indicates the class can only have static members and you cannot
create an instance of it. This is used for stateless functionality (for example
a type that just defines extension methods, or utility methods). You can also
declare a member static on a non-static class. This allows you to attach
functionality to a type without having to instantiate it.
abstracts define the basic structure and functionality shared by all
derivative types, but cannot be used by themselves. Think of them as, I
suppose, a blue print and a contract. This is a core concept for OOP.
Static Class: Declared with Static keyword, methods in Static Class are
also static along with variables of the class.
This class cannot be instantiated, i.e we cannot have objects of this
class. To access methods of this class, you can directly use classname.method.
Also, this class cannot be inherited.
Abstract Class: Declared with abstract keyword,
this class is primarily created as an Inheritable class. An abstract class
enables other classes to inherit from this class but forbids to instantiate.
One can inherit from an abstract class but we cannot create objects of an
abstract class. Abstract class can have abstract as well as non-abstract
methods. Abstract methods are those which are not having method definition.
In loosely coupled architecture, services and
applications:-
·
Serve a single purpose or have a single
responsibility
·
Have a clear interface for communication
·
Have less dependencies on each other
·
Can be agnostic to outside concerns
·
Can change their underlining technology without
affecting the rest of the application
·
Are easier to automate tests
·
Can be deployed independently without affecting
the rest of ecosystem
·
Can scale independently
·
Can fail independently
·
Allow your teams to work independently, without
relying on other teams for support and services
·
Allow small and frequent changes
·
Have less technical debts
·
Have a faster recovery from failure
No comments:
Post a Comment