C# Notes
C# Notes
. To create a User Defined datatype or structure, we will need to use struct Keyword.
1
2. Under a structure, we can have data types and methods.
3. When we declare a variable inside a structure, it should use a proper access specifier.
4. Access specifier is used to expose the variable outside the class or structure.
5. There are 3 types of access specifier :
5.1 Public
5.2 Private
5.3 Protected
5.4 Internal
5.5 Protected Internal.
6. When we are declaring a variable without an access specifier, by default it will
consider it as a private access specifier.
7. We can explicitly define the access specifier as public.
8. Under the Main method, we need to declare user defined structure.
General _general;
9. We can use the structure, whatever the way we need.
Sample Program :
using System;
amespace Sample_UserDefinedDatatype
n
{
truct General
s
{
public int _firstValue;
public int _secondValue;
public int _result;
}
class Add {
}
Method:
It is a block/set of code containers surrounded by a specific name, which is called a
Method.
Signature:
}
Constructor:
Types of Constructor:
.
1 efault Constructor
D
2. Parameterized Constructor
3. Copy Constructor
4. Static Constructor
5. Private Constructor
. Default Constructor:
1
Syntax: public ClassName() { }
Description: Default constructors are parameterless constructors provided by the
compiler if no constructor is defined in the class. They initialize fields to their default
values.
Example:
/ / Default Constructor
public Person()
{
Name = "John Doe";
Age = 30;
}
}
Example:
/ / Parameterized Constructor
public Person(string name, int age)
{
Name = name;
Age = age;
}
}
/ / Copy Constructor
public Person(Person otherPerson)
{
ame = otherPerson.Name;
N
Age = otherPerson.Age;
}
}
Example:
using System;
/ / Static constructor
static MyClass()
{
creationTime = DateTime.Now;
}
lass Program
c
{
static void Main()
{
// Access the creation time
DateTime time = MyClass.GetCreationTime();
Console.WriteLine($"Object created at: {time}");
}
}
/ / Private Constructor
private Singleton() { }
6. Destructor
yntax: ~ClassName() { }
S
Description: Destructors are used to release resources held by an object before it is
destroyed by the garbage collector. They are less commonly used in C# due to the
presence of garbage collection.
Inheritance:
Inheritance is the process in which a child class inherits properties of the parent class.
Types of Inheritance:
. Single Inheritance
1
2. Multilevel Inheritance
3. Multiple Inheritance
4. Hierarchical Inheritance
5. Hybrid Inheritance.
Note: C# allows only 2 types of inheritance, that is, single and multilevel inheritance.
Multiple inheritance is not allowed in C#, but could be achieved with the help of
interfaces.
In C# Multiple inheritance can be achieved through interfaces. Interfaces inC#
provide a way to define contracts for classes without specifying the
implementation. A classcanimplementmultipleinterfaces,allowingittoinherit
behavior from multiple sources
Example:
using System;
lass Program
c
{
static void Main()
{
Duck duck = new Duck();
duck.Fly(); // Duck is flying
duck.Swim(); // Duck is swimming
}
}
Interfaces:
n interface in C# is a reference type that defines a contract for what a class must
A
implement. It contains onlythedeclarationofmethods,properties,events,orindexers,
without providing any implementation.
Example:
Abstract Class
n abstract class in C# is a class that cannot be instantiated on its own and may
A
contain abstract methods, which are declared without an implementation. Abstract
classes can also contain concrete methods with implementations.
Example:
olymorphism is the ability of an object to take on multiple forms. In OOP, it allows
P
objects of different classes to be treated as objects of a common superclass.
Types Of Polymorphism:
1. C ompile-Time Polymorphism (Static Binding): This is achieved through method
overloading and operator overloading.
2. Run-Time Polymorphism (Dynamic Binding): This is achieved through method
overriding.
Example:
Method Overloading:
Method Overriding:
ethod overridingallowsasubclasstoprovideaspecificimplementationofamethod
M
that is already provided by its superclass.
using System;
lass Program
c
{
tatic void Main()
s
{
Animal animal = new Dog();
animal.MakeSound(); // Output: Dog barks
}
}
Method Hiding:
Exception Handling:
xception handling is a mechanism in programming that allows you to deal with
E
unexpectedorexceptionalsituationsthatmayoccurduringtheexecutionofaprogram.
It helps in gracefully handling errors and prevents the program from crashing.
In C#exception handling is done using ̀try`, ̀catch`, ̀finally`, and ̀throw` keywords.
Here's a basic example:
using System;
lass Program
c
{
static void Main()
{
try
{
int[] numbers = { 1, 2, 3 };
Console.WriteLine(numbers[5]); // Trying to access an index out of bounds
}
catch (Exception ex)
{
Console.WriteLine("An error occurred: " + ex.Message);
}
finally
{
Console.WriteLine("Finallyblockalwaysexecutes,whetheranexceptionoccurs
or not.");
}
In this example, the ̀try` block contains code that might throwanexception(tryingto
access an index out of bounds in an array). If an exception occurs, the ̀catch` block
catches the exception, and you can handle it (printing an errormessageinthiscase).
The ̀finally` block is optional and is used toexecutecleanupcodethatshouldalways
run, whether an exception occurs or not.