You are on page 1of 22

To compile execute press Ctrl+F5

using System;// name space decalaration


class Program
{
static void Main(String[] args)
{
Console.WriteLine("Welcome to C# Training");// used to print a message to
console
}
}

Console class will present inside System namespace...we can write like this also if
you dont decalre System name space globally

System.Console

Using System declaration


--------------------------
The namespace declaration , using System indicates that you are using the System
namespace

A namespace is used to organize your code and is collection of classes, interfaces,


structs, enums and delegates

Main method is the entry point into your application

using System;
class Program
{
static void Main1()
{
Console.WriteLine("Welcome to C# Training");
}

static void Main()


{

Console.WriteLine("Welcome to .Net Training");


Main1();
}
}

Reading and writing to a console


--------------------------

using System;
class Program
{
static void Main()
{
// Prompt the user for his name
Console.WriteLine("Enter your name");

//Read the name from console


String username = Console.ReadLine();// As soon as you press enter this
line will execute

//Concatenate name with the helloword and print


Console.WriteLine("Hello " + username);

//Placeholder syntax to print name with hello


Console.WriteLine("Hello {0}" ,username);
}
}

2 ways to write to console


------------
a) Concatenation
b) Place holder syntax - Most preferred

Note: C# is case sensitive

Built in Datatypes in C#
-------------
signed datatype has both negative and positive values
unsigned has only positive values

Boolean type - only true or false


Integral Types - sbyte, byte, short, ushort, int, unit, long, ulong, char
Floating Types - float and double
Decimal Types
String Type

We can extract min and max values of datatype like

using System;
using System;
class Program
{
static void Main()
{
int i = 0;
Console.WriteLine("Value : {0}", int.MinValue);
Console.WriteLine("Value : {0}", int.MaxValue);
}
}

String Type
---------
characters enclosed in double quotes

String name="Naresh";

Escape Sequences
--------------------
"\'Naresh\'";

using System;
class Program
{
static void Main()
{
int i = 0;
Console.WriteLine("Value : {0}", int.MinValue);
String name = "\'Naresh\'";
Console.WriteLine(name);
String lucky = @"C:\\Tummi\\Mayank\\Roy";
Console.WriteLine(lucky);
}
}

Verbatim Literal
-----------------
Verbatim literal is a string with an @symbol prefix , as in @"Hello".

Verbatim literals make escape sequences translate as normal printable characters to


enhance readability.

Example
----------------
Without Verbatim Literal: "C:\\pragim\\DotNet\\Training\\Csharp" - Less Readable
With Verbatim Literal: @"C:\pragim\DotNet\Training\Csharp" - Better Readable

Ternary Operator
-------------------
using System;
class Program
{
static void Main()
{
int number = 10;
bool isnumber = number == 10 ? true : false;
Console.WriteLine("Is Number is 10: {0}", isnumber);
}
}

Types in C#
---------------
In C# types are divided into 2 board ategories
Value Types - int, float, double, structs, enums etc.
Refrences Types - Interface, Class, delegates, arrays etc

By default value types are non nullable. To make them nullable use?
int i=0(i is non nullable, so i cannot be set to null, i=null willl generate
compile error)
int?j=0(j is nullable int, so j=null is legal)

using System;
class Program
{
static void Main()
{
bool? areYouMajor = null;
if(areYouMajor==true)
{
Console.WriteLine("He is major");
}
else
if(!areYouMajor.Value)
{
Console.WriteLine("He is not major");
}
else
{
Console.WriteLine("He did not selected");
}
}
}

using System;
class Program
{
static void Main()
{
int availableTickets;
int? ticketsOnSale = 100;
if(ticketsOnSale==null)
{
availableTickets = 0;
}
else
{
availableTickets = ticketsOnSale.Value;
}
Console.WriteLine("Available Tickets {0}", availableTickets);
}
}

In the above program instead of using if and else we can use Null Coalescing
operator ??

using System;
class Program
{
static void Main()
{
int availableTickets;
int? ticketsOnSale = null;
availableTickets = ticketsOnSale ?? 0;
Console.WriteLine("Available Tickets {0}", availableTickets);
}
}

Implicit & Explicit Conversion


-------------------------------
Implicit conversion is done by the compiler
1) When there is no loass of information if the conversion is done.
2) If there is no possibilty of throwing exceptions during conversion

Example: Converting an int to a float will not loose any data and no exception will
be thrown, henace an implicit conversion can be done.

Where as when converting a float to an int , we loose the fractional part and also
a possibility of overflow exception.Hence in this case an explicit conversion is
required. For explicit conversion we can use cast operator or the convert class in
C#

Implicit Conversion Program


-------------------------
static void Main()
{
int i = 100;
float f = i;
Console.WriteLine(f);
}

Output: 100

Explicit conversion using CAST operator


-----------------------
static void Main()
{
float f = 345.555F;
int i = (int)f;
Console.WriteLine(i);
}
Output: 345

static void Main()


{
float f = 34577777777.555F;
int i = (int)f;
Console.WriteLine(i);
}

Output: -2147483648

Beacause the int range is exceeded by float

Explicit conversion using Convert class


--------------------
static void Main()
{
float f = 123.456f;
int i=Convert.ToInt32(f);
Console.WriteLine(i);
}
Output: - 123

In Convert class we will be having several methods

static void Main()


{
float f = 34577777777.555F;
int i = Convert.ToInt32(f);
Console.WriteLine(i);
}

When we run this program we will get exception


Unhandled Exception: System.OverFlowException

Difference between Parse and TryParse


--------------------------
If the number is in string format you have 2 options - Parse() and TryParse()

Parse() method throws an exception if it cannot parse the value, where TryParse()
returns a bool indicating whether it succeeded or failed.

Use Parse() if you are sure the value will be valid , otherwise use TryParse()

static void Main()


{
String strnumber = "100";
int i = int.Parse(strnumber);
Console.WriteLine(i);
}
Output: 100

static void Main()


{
String strnumber = "100NM";
int i = int.Parse(strnumber);
Console.WriteLine(i);
}
}
Exception: SystemFormatException- Input String was not in a correct fromat

static void Main()


{
String strnumber = "100NM";
int result = 0;
bool isConversionSuccessful=int.TryParse(strnumber, out result);
if(isConversionSuccessful)
{
Console.WriteLine(result);
}
else
{
Console.WriteLine("Please enter a valid number");
}
}

Arrays
--------------
An array is a collection of similar data types.

static void Main()


{
int[] evennumbers = new int[3];
evennumbers[0] = 0;
evennumbers[1] = 2;
evennumbers[2] = 4;
Console.WriteLine(evennumbers[1]);
}

//intailize and assign values in the same line


----------------
int[] oddnumbers={1,2,3};

Advantages
---------
Arrays are strongly types

Disadvantages
----------------
Arrays cannot grow in size once intialized
Have to rely on integral indices to store or retrieve items from the array

If-else
-------
static void Main()
{
Console.WriteLine("Please enter hemanth cricket score");
int hemanth = int.Parse(Console.ReadLine());

Console.WriteLine("Please enter roshan cricket score");


int roshan = int.Parse(Console.ReadLine());

Console.WriteLine("Please enter dev cricket score");


int dev = int.Parse(Console.ReadLine());

if(hemanth>=roshan && hemanth>=dev)


{
Console.WriteLine("Hemanth scored highest and his runs are {0}",
hemanth);
}

else if(roshan>=dev)
{
Console.WriteLine("Roshan scored highest and his runs are {0}",
roshan);
}

else
{
Console.WriteLine("Dev scored highest and his runs are {0}", dev);
}
}

Difference Between && and &


--------------------
&& Checks only one condition & Checks both the conditions

Differeence Between || and |


-------------------
|| Checks only one condition | Checks both the conditions

Switch Statement
-----------
Multiple if else statements can be replaced with switch statement

static void Main()


{
Console.WriteLine("Please enter the number");
int number = int.Parse(Console.ReadLine());
switch(number)
{
case 1: Console.WriteLine("Number is one");break;
case 2: Console.WriteLine("Number is two");break;
case 3: Console.WriteLine("Number is three");break;
default: Console.WriteLine("Please enter the correct number");break;
}
}

switch(number)
{
case 1:
case 2:
case 3: Console.WriteLine("Your number is {0}",Number);break;
default: Console.WriteLine("Please enter the correct number");break;
}

Note: Case statements, with no code in between, creates a single case for multiple
values. A case without any code will automatically fall throough to the next case.
In this example, case 1 and case 2 will fall through and execute code for case 3

break statement: If break statement is used inside a switch statement, the control
will leave the switch statement

goto statement: You can either jump to another case statement, or to a specific
label

Warning: Using goto is a bad programming style. We can should avooid goto by all
means

static void Main()


{
int totalcoffeecost = 0;
Start:
Console.WriteLine("Please select the menu 1-Small, 2-Medium, 3-Large");
int userselection = int.Parse(Console.ReadLine());
switch(userselection)
{
case 1:
totalcoffeecost += 100;
break;
case 2:
totalcoffeecost += 200;
break;
case 3:
totalcoffeecost += 300;
break;
default: Console.WriteLine("Please select the valid options there in
the menu");
break;
}
Decide:
Console.WriteLine("Do you want to order again Yes or No");
String userdecision = Console.ReadLine();
switch(userdecision.ToUpper())
{
case "YES":
goto Start;
case "NO":
break;
default:
Console.WriteLine("Your choice {0} is invalid ... Please try
again.....",userdecision);
goto Decide;
}
Console.WriteLine("Thank for shopping visit again!!!");
Console.WriteLine("Total Bill {0}", totalcoffeecost);
}

while loop
-----------
1) while loop checks the condition first
2) If the condition is true, statements with in the loop are executed.
3) This process is repeated as long as the condition evaluates to true

Note: Dont forget to update the variable participating in the condition , so the
loop can end at some point.

static void Main()


{
Console.WriteLine("Enter the target number?????");
int targetnumber = int.Parse(Console.ReadLine());
int startnumber = 0;
while(startnumber<=targetnumber)
{
Console.WriteLine(startnumber);
startnumber += 2;
}
}

do while loop
---------------

for loop
----------
A for loop is very similar to while loop. In a while loop we do the intialization
at one place, condition check at aonther place, and modifying the variable at
another place, where as for loop has all of these at one place..

static void Main()


{
int[] numbers = new int[3];
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
for(int i=0;i<numbers.Length;i++)
{
Console.WriteLine(numbers[i]);
}
}

For Each Loop


-----------------
A for each loop is used to iterate through the items in a collection. For example,
for each loop can be used with arrays or collections such as ArrayList, HashTable
and Generic.

static void Main()


{
int[] numbers = new int[3];
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
foreach(int i in numbers)
{
Console.WriteLine(i);
}
}

Why methods
---------------
[attributes]
access-modifiers return-type method-name (parameters)
{
Method Body
}

Return type can be any valid datatype or void


Method name can be any meaningful name
Prarametrs are optional

class Program
{
public static void Main()
{
Program program = new Program();
program.evennumbers(10);
int result=program.add(10, 20);
Console.WriteLine(result);
}

public int add(int a,int b)


{
int sum = a + b;
return sum;
}

public void evennumbers(int target)


{
int start = 0;
while(start<=target)
{
Console.WriteLine(start);
start += 2;
}
}

static vs instance methods


----------------------
When a method is declaration includes a static modifier, that method is said to be
a static method.
When no static modifier is present, the method is said to be an instance method.

Static method is invoked using the classname, where as an instance method is


invoked using an instance of the class.

The difference between instance methods and ststic methods is that multiple
instances of a class can be created(or instantiated) and each instance has its own
separate method. However, when a method is static , there are no instances of that
method , and you can invoke only that one defination of the static method.

Method Parameter Types


------------------------
There are 4 different types of parameters a method can have

1) Value Parameters: Creates a copy of the parameter passed, so modifications does


not affect each other.

Pass By value
---------------
I and J are pointing to different memory locations. Operations one variable will
not affect the value of the other variable.

public static void Main()


{
int i = 0;
simplemethod(i);
Console.WriteLine(i);
}
public static void simplemethod(int j)
{
j = 100;
}

Output: 0

2) Reference Parameters: The ref method parameter keyword on a method parameter


causes a method to refer to the same variable that was passed into the method. Any
changes made to the parameter in the method will be reflected in that variable when
control passes back to the calling method.

Pass By Reference
-------------------
I anj J are poiniting to the same memory location. Operationd on one variable will
affect the value of the other variable.

public static void Main()


{
int i = 0;
simplemethod(ref i);
Console.WriteLine(i);
}
public static void simplemethod(ref int j)
{
j = 100;
}

Output: 100

Out Parameters
---------------
Use when you want a method to return more than one value.

public static void Main()


{
int Total = 0;
int Product = 0;
simplemethod(100, 200, out Total, out Product);
Console.WriteLine("Sum is {0} && Product is {1}", Total, Product);
}

public static void simplemethod(int firstNum, int lastNum, out int Sum, out int
product)
{
Sum = firstNum + lastNum;
product = firstNum * lastNum;
}
Parameter Arrays
----------------------
The params keyword lets you specify a method parameter that takes a varibale number
of arguments. You can send a comma-seprated list of arguments , or an array, or no
arguemnts.
Params keyword should be the last one in a method declaration, and only one params
keyword is permitted in a method declaration.

public static void Main()


{
int[] Numbers = new int[3];

Numbers[0] = 101;
Numbers[1] = 102;
Numbers[2] = 103;
Paramsmethod(Numbers);
}
public static void Paramsmethod(params int[] Numbers)
{
Console.WriteLine("There are {0} elements", Numbers.Length);
foreach(int i in Numbers)
{
Console.WriteLine(i);
}
}

Class?
-----------
If you want to create complex custom types, then we can make use of classes.

A class consists of data and bahaviour. Class data is represented by its fields and
behaviour is represented by its methods.

class Customer
{
String _firstname;
String _lastname;
public Customer(String firstname, String lastname)
{
this._firstname = firstname;
this._lastname = lastname;
}

public void print()


{
Console.WriteLine("Full Name is {0}",this._firstname+ "" +this._lastname);
}
}
class Program
{
public static void Main()
{
Customer c1 = new Customer("Maddu","Naresh");
c1.print();
}
}
class Customer
{
String _firstname;
String _lastname;
public Customer()
: this("No FirstName Provided", "No LastName Provided")
{
}
public Customer(String firstname, String lastname)
{
this._firstname = firstname;
this._lastname = lastname;
}
public void print()
{
Console.WriteLine("Full Name is {0}",this._firstname+ "" +this._lastname);
}

~Customer()
{
//clean up code
}

}
class Program
{
public static void Main()
{
Customer c1 = new Customer();
c1.print();
Customer c2 = new Customer("Tummi","Shireesha");
c2.print();
}
}

Purpose of a class constructor


-----------------------
The purpose of a class constructor is to intialize class fields. A class
constructor is automatically called when an instance of a class is created.

Constructors do not have return values and always have the same names as the class

Constructors are not mandatory. If we do not provide a constructor , a default


parameter less constructor is automatically provided.

Constructors can be overloaded by the number and type pf parameters

Static and Instance class memebers


--------------------
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 memeber.

static members are invoked using class name, where as instance members are invoked
using instances(objects) of the class.

An instance member belongs to specific instance(object) of a class. If i create a 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 a class are created.

Note: Class members= fields, methods,properties,events,indexers,constructors

class Circle
{
static float _PI;
int _radius;

static Circle()
{
Circle._PI = 3.141F;
}

public Circle( int radius)


{
this._radius = radius;
}

public float CalculateArea()


{
return _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(10);


float area2 = C2.CalculateArea();
Console.WriteLine("Area={0}", area2);
}
}

Why inheritance
---------------------
A lot of code between these 2 classes is duplicated

Inheritance is oen of the primary pillars of object oriented programming


It allows code reuse
Code reuse can reduce time and errors

Note: You will specify all the common fields, properties, methods in the base
class, which allows reusability. In the derived calss you will only have fields,
properties and methods, that are specific to them

Inheritance Syntax
--------------------
public class ParentClass
{
//Parent Class Implementation
}
public class DerivedClass : ParentClass
{
//Child Class Implementation
}

1) In this example DerivedClass inherits from ParentClass


2) C# supports only single class inheritance
3) C# supports multiple interface inheritance
4) Child class is a specialization of base class
5) Base classes are automatically instantiated before derived classes.
6) Parent Class constructor executes before ChildClass constructors

public class Employee


{
public String Firstname;
public String Lastname;
public String Email;

public void PrintFullName()


{
Console.WriteLine(Firstname + " " + Lastname);
}
}

public class FullTimeEmployee : Employee


{
public float YearlySalary;
}

public class PartTimeEmployee : Employee


{
public float HourlyRate;
}
class Program
{
public static void Main()
{
FullTimeEmployee FTE = new FullTimeEmployee();
FTE.Firstname = "Naresh";
FTE.Lastname = "Maddu";
FTE.YearlySalary = 5000;
FTE.PrintFullName();

PartTimeEmployee PTE=new PartTimeEmployee();


PTE.Firstname = "Sirisha";
PTE.Lastname = "Tummi";
PTE.HourlyRate = 78;
PTE.PrintFullName();
}
}

public class ParentClass


{
public ParentClass()
{
Console.WriteLine("Parent class constructor called");
}
public ParentClass(String Message)
{
Console.WriteLine(Message);
}
}

public class ChildClass : ParentClass


{
public ChildClass() : base("Derived class controlling Parent class")
{
Console.WriteLine("Child class constructor called");
}
}

class Program
{
public static void Main()
{
ChildClass cc=new ChildClass();
}
}

Method Hiding
------------
Use the new keyword to hide a base class member. you will get a compiler warning,
if you miss the new keyword.

Different ways to invoke a hidden base class member from derived class
-------------------------
1) Use base Keyword

public void PrintFullName()


{
base.PrintFullName();
//Console.WriteLine(FirstName + " " + LastName +"Sudheer Reddy");
}

2) Cast child type to parent type and invoke the hidden number

FullTimeEmployee FTE = new FullTimeEmployee();


FTE.FirstName = "Texperts";
FTE.LastName = "Inc";
((Employee)FTE).PrintFullName();

3) ParentClass PC=new ChildClass()


PC.HiddenMethod();

A base class reference variable can point to child class object

Employee FTE = new FullTimeEmployee();


FTE.FirstName = "Texperts";
FTE.LastName = "Inc";
FTE.PrintFullName();

Polymorphism
-----------------
Polymorphism is one of the primary pillars of object oriented programming
Polymorphism allows you to invoke derived class methods through a base class
reference during runtime.

In the base class the method is declared virtual, and in the derived class we
override the same method

The virtual keyword indicates, the method can be overridden in any derived class
public class Employee
{
public string FirstName="FN";
public string LastName="LN";

public virtual void PrintFullName()


{
Console.WriteLine(FirstName + " " + LastName);
}
}

public class PartTimeEmployee : Employee


{
public override void PrintFullName()
{
Console.WriteLine(FirstName + " " + LastName +"----- Part Time Employee");
}
}

public class FullTimeEmployee : Employee


{
public override void PrintFullName()
{
Console.WriteLine(FirstName + " " + LastName + "----- Full Time Employee");
}
}

public class TemporaryEmployee: Employee


{
public override void PrintFullName()
{
Console.WriteLine(FirstName + " " + LastName + "----- Temporary Employee");
}
}

class Program
{
public static void Main()
{
Employee[] employees = new Employee[4];
employees[0] = new Employee();
employees[1] = new PartTimeEmployee();
employees[2] = new FullTimeEmployee();
employees[3] = new TemporaryEmployee();

foreach(Employee e in employees)
{
e.PrintFullName();
}
}
}
Difference between method overriding and method hiding
-----------------------------------

Method overloading
-------------------
Function overloading and Method overloading terms are used interchangeably.

Method overloading allows class to have multiple methods with the same name but
with a different signature. So in C# functions can be overloaded based on the
number, type(int, float etc) and kind (Value, Ref or Out) of parameters

The signature of a method consists of the name of the method and the type , kind
(value reference or output) and the number of its format parameters. The signature
of a method does not include the return typr and the params modifier. So it is not
possible to overload a function , just based on the return type or params modifier.

Why Properties
--------------------
Making the class fields public and exposing to the external world is bad, as you
will not have control over what gets assigned and returned.

public 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 = -100;
Console.WriteLine("ID = {0} & Name = {1} & Passmark={2}", C1.Id, C1.Name,
C1.Passmark);
}
}
The problem with above program is
Problems with public fields
-------------
1) ID should always be non negative number
2) Name cannot be set to NULL
3) If Student Name is missing "No Name should be returned"
4) PassMark should be read only

Structs
----------------
Just like classes structs can have
1) Private Fields
2) Public Properties
3) Constructors
4) Methods

Object intializer syntax introduced in C# 3.0can be used to intialize either a


struct or a class

public struct Employee


{
private int _id;
private string _name;

public int ID
{
get { return _id; }
set { _id = value; }
}

public string Name


{
get { return _name; }
set { _name = value; }
}

public Employee(int id, string name)


{
this._id = id;
this._name = name;
}

public void printdetails()


{
Console.WriteLine("Id={0} && Name={1}", this._id, this._name);
}
}

class Program
{
public static void Main()
{

Employee e1 = new Employee(10, "Naresh");


e1.printdetails();

Employee e2 = new Employee();


e2.ID = 20;
e2.Name = "Siri";
e2.printdetails();

Employee e3 = new Employee


{
ID = 30,
Name = "Renuka"
};
e3.printdetails();
}
}

Classes Vs Structs
------------
A Struct is a value type where as a class is a reference type

All the differences that are applicable to value types and reference types are also
applicable to classes and stucts.

Structs are stored on stack, where as classes are stored on the heap.

Value types hold their value in memory where they are declared, but reference types
hold a reference to an object in memory.

Value types are destroyed immediatley after the scope is lost , where as for
refrence types only the refrenece variable is destroyed after the scope is lost.
The object is later destroyed by garbage collector.

When you copy a struct into another struct, a new copy of that struct gets created
and modification on one struct will not affect the values contained by the other
struct.

When you copy a class into another class, we only get a copy of the reference
variable. Both the reference variables point to the same object on the heap. So,
operations on one variable will affect the values contained by the other refreence
varaible.

Structs cant have destructors, but classes can have destructors.

Structs cannot have explicit parameter less constructor where as a class can

Struct cant inherit from another class where as a class can, Both structs and
calsses can inherit from an interface.

Exaples of structs in the .Net framework - int(System.Int32), double(System.Double)

Note 1: A class or a struct canot inherit from another struct. Struct are sealed
types

INterfaces
-----------------
We create interfaces using interface keyword. Just like classes interfaces also
contains properties, methods, delegates or events, but only declarations and no
implementations.
It is a compile time error to provide implementations for any interface member.
Interface members are public by default, and they dont allow explicit access
modifiers .
Interface cannot contain fields.
If a class or struct inherits from an interface, it must provide implementaion for
all interface memebers. Otherwise we get a compile time error.
A class or a struct can inherit from more than one interface at the same time , but
where as , a class cannot inherit from more than once class at the same time.
Interfaces can inherit from other interfaces. A class that inherits this interface
must provide implementation for all interface members in the entire interface
inheritance chain.
We cannot create an instance of an interface, but an interface reference variable
can point to a derived class object.

Interface Naming Convention: Interface names are prefixed with capital I


Explicit interface Implementation
------------------------
A class inherits from 2 interfaces and both the interfaces have the same menthod
name. How should the class implement the method for both the interfaces??

Answer is We are using Explicit Interface Implementation technique to solve this


problem.

Note: When a class explicitly implements, an interface memeber, the interface


memeber can no longer be accessed thru class reference variable, but only thru the
interface reference variable.

Access modifiers are not allowed on explicitly implemented interface members

interface I1
{
void details();
}

interface I2
{
void details();
}
class Program: I1,I2
{
public static void Main()
{
Program p = new Program();
((I1)p).details();
((I2)p).details();
}
void I1.details()
{
Console.WriteLine("First interface implemented");
}
void I2.details()
{
Console.WriteLine("Second interface implemented");
}
}

Abstract classes
--------------
The abstract keyword is used to create abstract classes.

An abstract class is incomplete and hence cannot be instantiated.


An abstract class can only be used as base class
An abstract class cannot be sealed
An abstract class may contain abstract members(methods,properties,indexers and
events), but not mandatory.
A non-abstract class derived from an abstract class must provide implementations
for all inherited abstract members.

If a class inherits an abstract class, there are 2 options availbale for that class
------------------------------
Option 1: Provide implementation for all the abstract members inherited from the
base abstract class.
Option 2: If the class does not wish to provide implementation for all the abstract
members inherited from the abstract class, then the class has to be marked as
abstract

public abstract class Customer


{
public abstract void print();
}
public class Program:Customer
{
public override void print()
{
Console.WriteLine("Modda");
}
public static void Main()
{
Customer c = new Program();//Customer refrence variable is pointing to
derived class object Program
c.print();

}
}

Abstract classes Vs Interfaces


--------------------
Abstract classes can have implementations for some of its members(Methods), but the
interface can t have implementation for any of its memebers.

Interfaces cannot have fields where as an abstract class can have fields.
An interface can inherit from another interface only and cannot inherit from an
abstract class where as an abstract class can inherit from another abstract class
or another interface.

A class can inherit from multiple interfaces at the same time, where a class cannot
inherit from multiple classes at the same time

Abstract class members can have access modifiers where as interface members cannot
have access modifiers

You might also like