C# Notes

You might also like

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

## types of application

- Desktop Applications
- Web Applications
- Mobile Applications

* c# .net is extension of c++


* J# .net is extension of java

## c# features
- Object oriented
- Platform Independent
- Language Independent

## Access Specifiers:
- It's a special kind of modifers using which we can define the scope of a type and
it's members.
- class can be public and internal only
- class by default is internal
- members of a class are by default private

** types -
* private
- access within the class only in which it is declared & in same project

* internal
- if we declare class or memeber as internal, it is accessible within the project
from child class or non child(different class) class

* protected
- members declared as protected are accessible within its class and inherited class
in same project or different project

* protected internal
- combo of protected & internal, if protected or internal is accessible than
protected internal is also accesible

* public
- accessed anywhere

## constructors
- It's a special method present under a class responsible for
initializing the variables of that class.

- The name of a constructor method is exactly the same name of the class in which
it was present and more over it's a non-value returning method.

- Each and every class requires this constructor if we want to create the instance
of that class.

- It's the responsibility of a programmer to define a constructor under his class


and if he fails to do so, on behalf of the programmer an implicit constructor gets
defined in that class by the compiler.

- Implicitly defined constructor by compiler are always public.

- to define constructors explicitly


syntax - <modifiers> <Name>(<parameter list>)
{
-Stmts;
}

* Types of Constructors:
1. Default or Parameter Less Constructor
- If a constructor method doesn't take any parameters then we call that as default
or parameter less. These constructors can be defined by a programmer explicitly or
else will be default implicitly provided there is no explicit constructor under the
class

2. Parameterized Constructor
- If a constructor method is defined with out any parameters we call that as
parameterized constructor and these constructors can be defined by the programmers
only but never can be defined implicitly.

3. Copy Constructor
- If we want to create multiple instances with the same values then we use these
copy constructors, in a copy constructor the constructor takes the same class as a
paramter to it.

eg -
class CopyConDemo
{
int x;
public CopyConDemo(int i)
{
x= i;
}

// copy constructor
public CopyConDemo(CopyConDemo obj)
{
x= obj.x;
}

public void Display()


{
Console.WriteLine("Value of x is: "+ x);
}

static void Main()


{
CopyConDemo cd1 = new CopyConDemo(10);
cd1.Display();
CopyConDemo cd2= new CopyConDemo(20);
cd2.Display();

// here op is 10, 20 but if want 10 in 2 op


we use copy constructor

CopyConDemo cd1 = new CopyConDemo(10);


cd1.Display();
CopyConDemo cd2= new CopyConDemo(cd1);
cd2.Display();
}
}

4. Static Constructor
- it is explicitly declared by using static modifier we
call that as Static Constructor. All the constructors we have defined till now are
non-static or instance constructors.

eg -
class Test
{
static Test() // Static constructor defined explicitly
{
}
public Test() // Implicit default constructor
{
}
}

1. If a class contains any static variables then only implicit static constructors
will be present or else we need to define them explicitly whereas non-static
constructors will be implicitly defined in every class (except static class)
provided we did not define them explicitly.

2. Static constructor are responsible in initializing static


variables and these constructors are never called explicitly they are implicitly
called and more over these constructor are first to execute under any class.

3. Static constructors can't be parameterized so overloading static constructors is


not possible becoz static method are
first to excecute and we donot even get time to even pass parameters and implicitly
called

eg 1 -

class StaticConstructureDemo
{
static StaticConstructureDemo()
{
Console.WriteLine("Static Constructure is called
first");
}
static void Main()
{
// when main is called first Static Constructure is
called
}
}

eg 2 -

class StaticConstructureDemo
{
static StaticConstructureDemo()
{
Console.WriteLine("Static Constructure is called
first");
}
static void Main()
{
Console.WriteLine("Main method is called
second");
// when main is called first Static Constructure is
called and then Main method
}
}

## Static Constructors vs Non Static Constructor

- If a constructor is explicitly declared by using a static


modifier we call that constructor as static constructor whereas rest of other are
non-static constructors only.

- Constructors are responsible for initializing fields/variables of a class, so


static fields are initialized by static constructors and non-static fields are
initialized by non-static constructors.

- Static constructors are implicitly (meaning it is first to excecute when class is


created)called whereas non-static
constructors must be explicitly called.

- Static constructors executes immediately once the execution of a class starts and
more over it's the first block of code to run under a class whereas non-static
constructors executes only after creating the instance of class as well as each and
every time the instance of class is created.

- In the life cycle of a class static constructor executes one and only one time
whereas non-static constructor executes for zero times if no instances are created
and "n" times if "n" instances are created.

- Non-static constructors can be parameterized but static


constructors can't have any parameters because static constructors are
implicitly(gets called as soon as class is executed) called

- Non-Static constructors can be overloaded where as static


constructors can't be overloaded(donot get time to pass parameter).

- Every class contains an implicit constructor if not defined


explicitly and those implicit constructors are defined based on the following
criteria.

- Static constructors are implicitly defined only if that class contains any static
fields or else that constructor will not be present at all.

## Types of variable
1) non static/ instance
2) static
3) constants
4) ReadOnly

- If a variable is explicitly declared by using the static modifer or else if a


variable is declared under any static block then those variables are static where
as rest of the other are non-static.

- Note : Static members of a class doesn't require the instance of class for
initializtion or execution also,where as non-static members of a class require the
instance of class
both for initialization and execution.

- Static variables of a class are initialized immediately once the execution of


class starts where as instance variables are initialized only after creating the
class instance as well
as each and every time the instance of class is created.

- In the life cycle of a class a static variable is initialized one and only one
time whereas instance variables are initialized for "0" times if no instance are
created and "n" times if "n" instances are created.

- Initialization of instance variables is associated with instance creation &


constructor calling,so instance variables can be initialized thru the constructor
also.

- If a variable is declared by using the keyword "const" we call it as a constant


variable and these constant variables can't be modified once after their
declaration, so it's must to initialize constant variables at the time of
declaration only.
eg - const float pi=3.14f;

- The behaviour of constant variables will be similar to the behaviour of static


variables i.e. initialized one and only one time in the life cycle of a class

- The only difference between a static and constant variable is static variables
can be modified whereas constant variables can't be modified.

- If a variable is declared by using the "readonly" keyword we call that variable


as a readonly variable and these variables also can't be modified like constants
but after initialization.It's not compulsory to initialize a readonly variable at
the time of declaration,they can also be initialized under the constructor.

- The behaviour of readonly variables will be similar to the behaviour of non-


static variables,i.e. initialized only after creating the instance of class and
once for each instance of the class is created.

- The only difference between readonly and instance variables is instance variables
can be modified but not readonly variables.

- Constant variable is a fixed value for the whole class where as readonly
variables is a fixed value specific to an instance of class.

## Inheritance:
- It's a mechanism of consuming the members of one class in another class by
establishing parent/child relationship between the classes which provides re-
usablity.

Note: In inheritance, child class can consume members of it's parent class as if it
is the owner of those members (expect private members of parent) including
constructors which are by default private if no access specifier is mentioned
syntax -
<modifiers> class <child class> : <parent class>

class A
{
Members;
}
class B:A
{
Consuming the members of A from here;
}

1. Parent classes constructor must be accessible to


child class, otherwise inheritance will not be possible in case if parent class
constructor is made private which is by default private so need to make it public
explicitly

2. In inheritance child class can access parent classe


members but parent classes can never access any
member that is purely defined under the child class.

3. parent class reference can point to object of


child class but here parent class cannot call methods defined in child class, it
can call only methods defined in parent class

* types of inheritance
- single
- multi level
- hierchial
- hybrid (combo of multiple and hierchial)
- multiple

- in c# single, multi level, hierchial are supported

4. In the first point we learnt when ever child class instance


is created, child class constructor will implicitly call its
parent classes constructor but only if the constructor is
parameter less, where as if the constructor of parent class is
parameterized, child class constructor can't implicitly call
it's parent's constructor, so to overcome the problem it is the responsibility of
the programmer to explicitly call parent
classes constructor from child class constructor and pass
values to those parameters. To call parent's constructor from
child class we need to use the "base" keyword

eg -

class Class1
{
public Class1(int i)
{
Console.WriteLine("Class1 constructor is called: " + i);
}
public void Test1()
{
Console.WriteLine("Method 1");
}
public void Test2() {
(Console.WriteLine("Method 2");
}
}

class Class2 : Class1


{
public Class2(): base(10)
{
Console.WriteLine("Class2 constructor is called");
}
public void Test3()
{
Console.WriteLine(Method 3");
}
static void Main()
{
Class2 = new Class2();
}
}

## method overloading

- depands on no of paramters, types and sequence of mentioning parameters


- return type are not considered becoz there is problem of identification if 2
methods have same name

## Method Overriding:
-It's an approach of re-implementing a parent classes method under the child class
with the same signature.
eg -
Class1
Test()
Class2 : Class1
Test()

** Overloading:
1. In this case we define multiple methods with the same name by changing their
parameters.
2. This can be performed either within a class as well as between parent child
classes also
3. While overloading a parent classes method under the child
class, child class doesn't require to take any permission from the parent class

eg -
Class1
Show()
Show(int i) // overloading in same class
virtual Test() // virtual keyword is used for overriding
Class 2 : Class1
Show(string i) // overloading in different class
override Test() // overriding in different class

** Overriding:
1. In this case we define multiple methods with the same name and same parameters.
2. This can be performed only between parent child classes can
never be performed with in the same class.
3. While overriding a parent's method under child class, child
class requires a permission from it's parent.

Note: If we want to override a parent's method under the child


class first that method should be declared by using the "virtual" modifier in
parent class
- using "virtual" keyword in parent method parent gives permission to child to
override the method

- Any virtual method of the parent class can be overriden by the child if
required(may or maynot) by using the "override" modifier.
- it is on that whether we want to override a parent method by
declaring "override" keyword

## Method Hiding/Shadowing:
- Method overriding is an approach of re-implementing a parent
classes method under the child class exactly with the same name and signature.

- Method Hiding/Shadowing is also an approach of re-implementing a parent classes


method under the child class exactly with the same name and signature.

- -In th first case child class re-implements it's parent classes methods which are
declared as virtual, where as in the second case child class can re-implement any
parent's method even if the method is not declared as virtual by mentioning "new"
keyword instead of override method but mentioning "new" is optional

- after re-implementing parent classes methods under child classe, the child class
instance will start calling the local methods only ie the re-implemented methods,
but if required in any case we can also call the parent classes methods from child
classes by using 2 approaches.

1. By creating the instance of parent class under child class we can call parent's
methods from child class.
2. By using the "base" keyword also we can call parent's method from child class,
but keywords like this and base can't be used from static blocks.

eg -

class Parent()
{
public virtual void Test1() {}
public virtual void Test2() {}
}
class Child : Parent
{
public override void Test1(){} // method overriding
public override void Test2(){} // method overriding
public new void Test1() {} // method hiding
public void Test2() {} // method hiding

// this will call parent methods and base.methodname is


written in different method
public void ParentTest1()
{
base.Test1(); // call parent method like super
}
public void Parent Test2()
{
base.Test2();
}
static void Main()
{
Child c = new Child();
c.ParentTest1()
}
}

## operator overloading

syntax -

<modifiers> static <return type> operator <opt>(<operand


types>)
{
Logic
}

public static int operator +(int x, int y) {


return x + y;
}

## Abstract

-If a method is declared as abstract under any class then the


child class of that class is responsible for implementing the
method

- if a child class donot implement abstract method of parent class then child class
cannot access the non abstract methods of parent class.

- cannot create instance of abstract class

eg -
abstract class Class1
{
public abstract void Show();
}
class Class2:Class1
{
public override void Show() // Mandatory
{
-Implementation
}
}

## Interface
syntax -
<modifiers> interface <Name>
{
-Abstract Member Declarations here
}

- The default scope the members of an interface is public but in class default
scope the members private

- The default scope the methods of an interface is public, abstract


eg -
namespace interfaceproject
{
interface TestInterface
{
int x; // not valid, can't declare
void Add(int a,int b);
}
}

- We can't declare any fields/variables under an interface.

- If required an interface can inherit from another interface.

- Every member of an interface should be implemented under the


child class of the interface with out fail, but while implementing we dont require
to use "override" modifier just like we have done in case of abstract class or in
class.

eg -
namespace interfaceproject
{
interface TestInterface1
{
void Add(int a,int b);
}
interface TestInterface2 : TestInterface1
{
void sub(int a,int b);
}

class Implementation : TestInterface2


{
// public is used in child class
public void Add(int a,int b)
{
Console.WriteLine(a+b);
}
public void Sub(int a, int b)
{
Console.WriteLine(a-b);
}
static void Main()
{
Implementation obj=new Implementation();
obj.Add(100,30); obj.Sub(78,23);
}
}
}

## Properties(similar to getter and setter methods)

- Property is a member of class using which we can expose values associated with a
class to the outside environment.

- syntax - <modifiers> <Return type> <Name>


{
get{ <stmt's> } // Get Accessor
set{ <stmt's> } // Set Accessor
}

eg -

public class Circle


{
double _Radius=12.34; // by default private
public double Radius
{
// here we can set conditions on the get and set accessors
get { return _Radius; }
set { _Radius = value; } // value is implicit

or
set
{
if(value > _Radius)
{
_Radius = value;
}
}
}
}
public class TestCircle
{
static void Main()
{
Circle c = new Circle();
double radius = c.Radius;
c.Radius = 56.78;
}
}

## Indexer
- fields can be accessed in 3 ways-
1) declare the fields as public but not recommended
2) use properties(set and get methods)
3) indexers

syntax -
<modifiers> <returntype> this[int index] or [string fieldname]
{
get { <stmts> } // Get Accessor
set { <stmts> } // Set Accessor
}

- "this" is used to say that it is defined on current class

- it is member of a class and if we define indexers in a class then that class


behaves like a virtual array and it gives permission to access the members of class
like a array

eg -

public class Employee


{
int Eno;
double Salary;
string Ename,Job, Dname, Location;
public Employee(int Eno,string Ename, string Job,double
{
this.Eno = Eno;
this.Ename= Ename;
this.Job Job;
this.Salary Salary;
this.Dname= name;
this.Location= Location;
}

public object this[int index]


{
get
{
if(index == 0)
return Eno;
else if(index == 1)
return Ename;
else if(index == 2)
return Job;
else if(index == 3)
return Salary;
else if(index == 4)
return Dname;
else if(index == 5)
return Location:
return null;
}

set
{
//return type is object but value is int, string, double
so typecasting is required
if(index == 0)
Eno = (int)value;
else if(index == 1)
Ename = (string)value;
else if(index == 2)
Job = (string)value;
else if(index == 3)
Salary = (double)value;
else if(index == 4)
Dname = (string)value;
else if(index == 5)
Location=(string)value;
}
}
}

class TestEmployee
{
static void Main()
{
Employee Emp= new Employee(1001, "Scott",
"Manager","25000", "sales", "mumbai');

Console.WriteLine("Eno: " + Emp[0]);


Console.WriteLine("Ename: "+Emp[1]);
Console.WriteLine("Job: " + Emp[2]);
Console.WriteLine("Salary:"+Emp[3]);
Console.WriteLine("Dname: "+Emp[4]);
Console.WriteLine("Location:"+ Emp[5]);

Emp[3]= "Sr. Manager";


Emp[4]= 25000.00;
Console.ReadLine();
}
}

## Delegates
- methods can be accessed in 3 ways-
1) by instance if method is non static
2) by class name
3) by delegate

- It's a type safe function pointer.


- A delegate holds the reference of a method and then calls the method(static or
non static) for execution.

- To call a metho d by using a delegate we have 3 steps:

1. Define a delegate

<modifiers>] delegate void type<Name> ([<parameter list>])


eg -

- syntax is similar to method except delegate is used


public delegate void AddDelegate(int x, int y);
public void AddNums(int a, int b)

public delegate string SayDelegate(string str);


public static string SayHello(string name)

2. Instantiating the delegate.

AddDelegate ad= new AddDelegate(p.AddNums);


SayDelegate sd=new SayDelegate(Program.SayHello);

3. Now call the delegate by passing required parameter values,so that internally
the method which is bound with the delegate gets executed.

ad(100, 50); or ad.Invoke(100, 50);


sd("akash");

eg -

namespace DelegatesProject
{
// Step 1:Defining a delegate
public delegate void AddDelegate(int x,int y);
public delegate string SayDelegate(string str);

class Program
{
public void AddNums(int a, int b)
{
Console.WriteLine(a +b);
}

public static string SayHello(string name)


{
return"Hello"+name;
}

static void Main(string[]args)


{
Program p= new Program();

// Instantiating the delegate.


// AddNums is non static so called by object
// ad holds reference of AddNums
AddDelegate ad = new AddDelegate(p.AddNums);
ad(100, 50);

SayDelegate sd =new SayDelegate(Program.SayHello);


sd("akash");
}
}

## multidelegate
- if return type is not void then the second method called will override the first
method o/p

namespace DelegateProject
{
// return type and parameters must be same in delegate
public delegate void RectDelegate(double Width,double
Height);

class Rectangle
{
public void GetArea(double Width,double Height)
{
Console.WriteLine(Width * Height);
}
public void GetPerimeter(double Width,double Height)
{
Console.WriteLine(2 * (Width + Height));
}
static void Main()
{
Rectangle rect = new Rectangle()
RectDelegate obj = new RectDelegate(rect.GetArea);
or
RectDelegate obj = rect.GetArea;
// binding to more than one delegate
obj += rect.GetPerimeter;

obj.Invoke(12.34,56.78);
}
}
}

## Anonymous Methods

* using delegates

namespace DelegatesProject
(
public delegate string GreetingDelegate(string name);
class AnonymousMethods
{
public static string Greetings(string name)
{
return "Hello " + name + " a very good morning!";
}

static void Main()


{
GreetingsDelegate obj = new Greetings
Delegate(Greetings);
string str = obj.Invoke("Scott");
Console.WriteLine(str);
}
}
}

* using Anonymous delegates


- method is defined in Anonymous method using "delegate"

namespace DelegatesProject
(
public delegate string GreetingDelegate(string name);
class AnonymousMethods
{
static void Main()
{
GreetingsDelegate obj = delegate(string name)
{
return "Hello " + name + " a very good morning!";
}

string str = obj.Invoke("Scott");


Console.WriteLine(str);
}
}
}

* using Lambda expression


- method is defined in Anonymous method using "delegate"

namespace DelegatesProject
(
public delegate string GreetingDelegate(string name);
class LambdaMethods
{
static void Main()
{
GreetingsDelegate obj = (name) =>
{
return "Hello " + name + " a very good morning!";
}

string str = obj.Invoke("Scott");


Console.WriteLine(str);
}
}
}

## Exceptions
- Exception is necessary to avoid abrupt exit of the code

1. System Exception
- here exception instance is created by clr
- try {}
catch(Exception e) {}
finally{}

2. Application Exception
- here exception instance is created by developer
ApplicationException ex = new Application Exception("Error
Msg");
throw ex;
or

throw new ApplicationException("Error Msg");

** to create own exception class in Application Exception

- override the message property from ApplicationException


eg -

public class DivideByOddNoException : ApplicationException


{
public override string Message
{
get
{
return "Attempted to divide by odd number.";
}
}
}

class ThrowDemo
{
static void Main()
{
Console.Write("Enter 1st number:");
int x= int.Parse(Console.ReadLine());
Console.Write("Enter 2nd number:");
int y= int.Parse(Console.ReadLine());
if(y%2>0)
{
// throw new Application Exception("Divisor value can't
be odd no.");
throw new Divide ByOdd No Exception();
}
int z= x/y;
Console.WriteLine("The result is: " + z);
Console.WriteLine("End of Program.");
}
}

## Structures

- Structures in C Language can contain only fields in it where as structures in C#


can contain most of the members what a class can contain like, Fields, Methods,
Constructors, Properties, Indexers, Operator Methods etc.

syntax -

[<modifiers>] struct <Name>


{
-Define members here
}

- Difference between Class and Structure:


1. Class is a reference type whereas structure is a value type.
2. Memory allocation for instances of class is performed on
Managed Heap whereas memory allocation for instances of structure is performed on
Stack.
3. We use class for representing an entity with larger volumes of data whereas we
use structures for representing smaller volumes of data.

Note: All pre-defined data types under the libraries of our


language which comes under reference type category E.g .: String and Object are
classes, whereas all the pre-defined data types which come under value type
category E.g .: int (Int32), float (Single), bool (Boolean) are structures.

4. In case of a class "new" is mandatory for creating the instance whereas in case
of a structure it is only optional.

5. Fields of a class can be initialized at the time of declaration whereas it's not
possible with fields in structure.

Note: If the structure contain any fields then we need to


initialize those fields either by explicitly calling the default constructor with
the help of "new" or else if we are not using "new" for creating the instance we
need to explicitly assign value to the field referring it through the instance and
assign value.

6. We can define any constructor under the class that is either parameterless or
parameterized and if no constructor is defined then there will be an implicit
constructor which is default whereas in case of a structure default constructor is
always implicit and can't be defined explicitly again, what we can define is only
parameterized constructor.

7. Class can be inherited by other classes, whereas structure


can't be inherited by other structures i.e. a structure doesn't support
inheritance.

8. A class can implement an interface same as that a structure


also can implement an interface.

## Enumeration
- it is set of named constant values
- A enum is a user-defined type, so it always better to define an Enum directly
under the namespace, but it is also possbile to define a Enum under a class or
structure also.

Syntax -

<modifiers> enum <Name> [: <type>]


{
-List of named constant values
}

ex -

namespace enum
{
public enum Days
{
Monday,Tuesday,Wednesday,Thursday,Friday
}
class TestClass
{
static void Main()
{
Days d = (Days)1; // Tuesday
or
Days d = Days.Monday;
Console.WriteLine((int)d);
Console.ReadLine();
}
}
}

You might also like