Professional Documents
Culture Documents
C# Notes
C# Notes
C# Notes
- Desktop Applications
- Web Applications
- Mobile Applications
## 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.
* 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;
}
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.
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 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.
- 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
- 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.
- 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.
- The only difference between a static and constant variable is static variables
can be modified whereas constant variables can't be modified.
- 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;
}
* types of inheritance
- single
- multi level
- hierchial
- hybrid (combo of multiple and hierchial)
- multiple
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");
}
}
## method overloading
## 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.
- 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.
- -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
## operator overloading
syntax -
## Abstract
- if a child class donot implement abstract method of parent class then child class
cannot access the non abstract methods of parent 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
eg -
namespace interfaceproject
{
interface TestInterface1
{
void Add(int a,int b);
}
interface TestInterface2 : TestInterface1
{
void sub(int a,int b);
}
- Property is a member of class using which we can expose values associated with a
class to the outside environment.
eg -
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
}
eg -
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');
## Delegates
- methods can be accessed in 3 ways-
1) by instance if method is non static
2) by class name
3) by delegate
1. Define a delegate
3. Now call the delegate by passing required parameter values,so that internally
the method which is bound with the delegate gets executed.
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);
}
## 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!";
}
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!";
}
namespace DelegatesProject
(
public delegate string GreetingDelegate(string name);
class LambdaMethods
{
static void Main()
{
GreetingsDelegate obj = (name) =>
{
return "Hello " + name + " a very good morning!";
}
## 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
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
syntax -
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.
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.
## 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 -
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();
}
}
}