SlideShare a Scribd company logo
• Effort by :
Name Enrollment no.
• Dumasia Yazad H. 140420107015
• Gajjar Karan 140420107016
• Jinay Shah 140420107021
• Jay Pachchigar 140420107027
1
Computer (Shift-1) 6th year
C# .NET
LANGUAGE FEATURES AND CREATING .NET PROJECTS,
NAMESPACES CLASSES AND INHERITANCE , EXPLORING
THE BASE CLASS LIBRARY -, DEBUGGING AND ERROR
HANDLING , DATA TYPES
2
Some of the feature of Visual C# in .NET are:
1.Simple modern, Object Oriented Language
2.Aims to combine high productivity of Visual Basic and the raw power of C++.
3.Common Execution engine and rich class libraries
4.MS JVM equivalent is Common Language Run time(CLR)
5.CLR accommodates more then one language such C#,ASP,C++ etc
6.Source code Intermediate Language (IL) (JIT Compiler) Native code
7.Class and Data types are common to .NET Language
8.Develop Console applications, Windows applications & web app using C#
9.In C#, MS has taken care of C++ problem like memory management, pointers, etc.
10.It supports Garbage collection, Automatic memory management and a lot.
Language Features And creating .NET project 3
Language Features And creating .NET project
Windows Store App
Windows
Client
Office
Enterprise
WebsitesComponents
Mobile Apps
Backend
Service
4
Namespaces
A namespace is designed for providing a
way to keep one set of names separate
from another. The class names declared in
one namespace does not conflict with the
same class names declared in another.
5
using System;
namespace first_space
{
class namespace_cl {
public void func(){
Console.WriteLine("Inside first_space"); } } }
namespace second_space {
class namespace_cl {
public void func() {
Console.WriteLine("Inside second_space"); } } }
class TestClass {
staticc void Main(string[] args)
{
first_space.namespace_cl fc = new first_space.namespace_cl
second_space.namespace_cl sc = new second_space.namespace_cl
fc.func();
sc.func();
Console.ReadKey(); } }
Inside first space
Inside second space
Output:
Demonstrates use of namespaces:
6
Class And Inheritance
Classes in C# allow single inheritance and multiple interface inheritance. Each class can
contain methods, properties, events, indexers, constants, constructors, destructors, operators
and members can be static (can be accessed without an object instance) or instance member
(require you to have a reference to an object first)
Also, the access can be controlled in four different levels: public (everyone can access),
protected (only inherited members can access), private (only members of the class can access)
and internal (anyone on the same EXE or DLL can access)
7
Example of Class
public class Person{// Field
public string name;
// Constructor that takes no arguments.
public Person(){
name = "unknown"; }
// Constructor that takes one argument.
public Person(string nm)
{ name = nm; }
// Method
public void SetName(string newName)
{ name = newName; }
}
class TestPerson
{
static void Main()
{
// Call the constructor that has no parameters.
Person person1 = new Person();
Console.WriteLine(person1.name);
person1.SetName(“Jinay Shah");
Console.WriteLine(person1.name);
// Call the constructor that has one parameter.
Person person2 = new Person(“Karan Gajjar");
Console.WriteLine(person2.name);
Person person3 = new Person(“Jay Pachchigar");
Console.WriteLine(person2.name);
Person person4 = new Person(“Yazad Dumasia");
Console.WriteLine(person2.name);
// Keep the console window open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
Output:
unknown
Jinay Shah
Karan Gajjar
Jay Pachchigar
Yazad Dumasia
8
Inheritance is the ability to create a class from another class, the "parent" class, extending the
functionality and state of the parent in the derived, or "child" class. It allows derived classes to
overload methods from their parent class.
Inheritance is one of the pillars of object-orientation.
Important characteristics of inheritance include:
1. A derived class extends its base class. That is, it contains the methods and data of its parent
class, and it can also contain its own data members and methods.
2. The derived class cannot change the definition of an inherited member.
3. Constructors and destructors are not inherited. All other members of the base class are
inherited.
4. The accessibility of a member in the derived class depends upon its declared accessibility in the
base class.
5. A derived class can override an inherited member.
Class Inheritance
9
C# does not support multiple inheritance. However, you can use interfaces to implement
multiple inheritance. The following program demonstrates this:
Multiple Inheritance in C#
using System;
namespace InheritanceApplication {
class Shape {
public void setWidth(int w)
{
width = w;
}
public void setHeight(int h)
{
height = h;
}
protected int width;
protected int height;
}
// Base class PaintCost
public interface PaintCost
{
int getCost(int area);
}
// Derived class
class Rectangle : Shape, PaintCost {
public int getArea() {
return (width * height);
}
public int getCost(int area) {
return area * 70;
}
}
class RectangleTester {
static void Main(string[] args)
{
Rectangle Rect = new
Rectangle();
int area;
Rect.setWidth(5);
Rect.setHeight(7);
area = Rect.getArea();
Console.WriteLine("Total
area: {0}", Rect.getArea());
Console.WriteLine("Total
paint cost: Rs {0}" ,
Rect.getCost(area));
Console.ReadKey(); } } }
10
Use Base keyword in inheritance
class A {
int i;
A(int n, int m) {
x = n;
y = m
Console.WriteLine("n="+x+"m="+y); }
}
class B:A {
int i;
B(int a, int b):base(a,b)//calling base
//class constructor and passing value
{
base.i = a;//passing value to base class
field
i = b;
}
public void Show() {
Console.WriteLine("Derived class i="+i);
Console.WriteLine("Base class i="+base.i); }
}
class MainClass {
static void Main(string args [] ) {
B b=new B(5,6);//passing value to derive
class constructor
b.Show(); }
}
OUTPUT
n=5m=6
Derived class i=6
Base class i=5
11
Exploring the Base Class Library
Within the Microsoft .NET framework, there is a component known…as
the base class library,
And this is essentially library of classes, interfaces, and value types that
you can. Use to provide common functionality in all of your .NET
applications.
The base class library is divided into namespaces to make locating that
functionality easier.
We've seen examples of using some of that functionality from the using
directives that exist at the top of our Program.cs file.We bring in
namespaces such as…System, and system.Collections.Generic,
System.Text, and System.Threading.Tasks.
12
Exploring the Base Class Library
And within these namespaces exist classes that perform certain
functionality that are related to the namespaces.
As an example, let's take a look at what…exists in the System.Text
namespace for functionality or for classes.
Now in order to do that, one of the…simplest ways is to bring up
our Object Browser window.…If we click on the View menu, we
can see that there's…a window called Object Browser, and the
shortcut key combination is Ctrl+ALT+J.
13
Exception Handling
An exception is a problem that arises during the execution of a program.
C# exception handling is built upon four keywords:
o Try: A try block identifies a block of code for which particular exceptions will
be activated. It's followed by one or more catch blocks.
o Catch: A program catches an exception with an exception handler at the
place in a program where you want to handle the problem. The catch
keyword indicates the catching of an exception.
o Finally: The finally block is used to execute a given set of statements,
whether an exception is thrown or not thrown.
For example, if you open a file, it must be closed whether an
exception is raised or not.
o Throw: A program throws an exception when a problem shows up. This is
done using a throw keyword.
14
Syntax 15
C# exceptions are represented by classes.
The exception classes in C# are mainly directly or indirectly
derived from the System.Exception class.
Some of the exception classes derived from the System.
Exception class are the System.ApplicationException and
System.SystemException classes
16
class Program {
public static void division(int num1, int num2)
{ float result=0.0f;
try
{
result = num1 / num2;
}
catch (DivideByZeroException e)
{
Console.WriteLine("Exception Error !! n divid by zero !!");
// Console.WriteLine("Exception caught: {0}", e);
}
finally {
Console.WriteLine("Result: {0} ", result);
}
}
static void Main(string[] args) {
division(10,0);
Console.ReadLine();
} }
17
User Defined Exception
using System;
namespace ExceptionHandling {
class NegativeNumberException:ApplicationException
{
public NegativeNumberException(string message)
// show message
}
}
if(value<0)
throw new NegativeNumberException(" Use Only Positive
numbers");
18
THE COMMON TYPE SYSTEM (CTS)
String Array ValueType Exception Delegate Class1
Multicast
Delegate
Class2
Class3
Object
Enum1
Structure1Enum
Primitive types
Boolean
Byte
Int16
Int32
Int64
Char
Single
Double
Decimal
DateTime
System-defined types
User-defined types
Delegate1
TimeSpan
Guid
19
Not all languages support all CTS types and features
C# supports unsigned integer types, VB.NET does not
C# is case sensitive, VB.NET is not
C# supports pointer types (in unsafe mode), VB.NET does not
C# supports operator overloading, VB.NET does not
CLS was drafted to promote language interoperability
vast majority of classes within FCL are CLS-compliant
20
MAPPING C# TO
CTSLanguage keywords map to common CTS classes:
Keyword Description Special format for literals
bool Boolean true false
char 16 bit Unicode character 'A' 'x0041' 'u0041'
sbyte 8 bit signed integer none
byte 8 bit unsigned integer none
short 16 bit signed integer none
ushort 16 bit unsigned integer none
int 32 bit signed integer none
uint 32 bit unsigned integer U suffix
long 64 bit signed integer L or l suffix
ulong 64 bit unsigned integer U/u and L/l suffix
float 32 bit floating point F or f suffix
double 64 bit floating point no suffix
decimal 128 bit high precision M or m suffix
string character sequence "hello", @"C:dirfile.txt"
21
EXAMPLE
• An example of using types in C#
• declare before you use (compiler enforced)
• initialize before you use (compiler enforced)
public class App
{
public static void Main()
{
int width, height;
width = 2;
height = 4;
int area = width * height;
int x;
int y = x * 2;
...
}
}
declarations
decl + initializer
error, x not set
22
BOXING AND UNBOXING
• When necessary, C# will auto-convert value <==> object
• value ==> object is called "boxing"
• object ==> value is called "unboxing"
int i, j;
object obj;
string s;
i = 32;
obj = i; // boxed copy!
i = 19;
j = (int) obj; // unboxed!
s = j.ToString(); // boxed!
s = 99.ToString(); // boxed!
23
USER-DEFINED REFERENCE
TYPES• Classes!
• for example, Customer class we worked with earlier…
public class Customer
{
public string Name; // fields
public int ID;
public Customer(string name, int id) //
constructor
{
this.Name = name;
this.ID = id;
}
public override string ToString() // method
{ return "Customer: " + this.Name; }
}
24
25

More Related Content

What's hot (20)

PDF
Intro to Deep Learning for Medical Image Analysis, with Dan Lee from Dentuit AI
Seth Grimes
 
PDF
String handling(string class)
Ravi_Kant_Sahu
 
PDF
Race condition
Михаил Фирстов
 
PPTX
Discuss the scrollable result set in jdbc
manojmanoj218596
 
PPTX
C++ compilation process
Rahul Jamwal
 
PPTX
Indexing with MongoDB
MongoDB
 
PPTX
Perl names values and variables
sana mateen
 
PDF
Linux 4.x Tracing Tools: Using BPF Superpowers
Brendan Gregg
 
PPT
Sortingnetworks
vikram singh
 
PPT
Input and output in C++
Nilesh Dalvi
 
PPSX
ARIES Recovery Algorithms
Pulasthi Lankeshwara
 
PDF
Python Basics
tusharpanda88
 
PPTX
Functions in c
kalavathisugan
 
PDF
“An Introduction to Data Augmentation Techniques in ML Frameworks,” a Present...
Edge AI and Vision Alliance
 
PDF
C Programming Project
Vijayananda Mohire
 
PDF
Little o and little omega
Rajesh K Shukla
 
PDF
Mastering GC.pdf
Jean-Philippe BEMPEL
 
PPTX
Data Augmentation
Md Tajul Islam
 
PDF
Matching networks for one shot learning
Kazuki Fujikawa
 
Intro to Deep Learning for Medical Image Analysis, with Dan Lee from Dentuit AI
Seth Grimes
 
String handling(string class)
Ravi_Kant_Sahu
 
Discuss the scrollable result set in jdbc
manojmanoj218596
 
C++ compilation process
Rahul Jamwal
 
Indexing with MongoDB
MongoDB
 
Perl names values and variables
sana mateen
 
Linux 4.x Tracing Tools: Using BPF Superpowers
Brendan Gregg
 
Sortingnetworks
vikram singh
 
Input and output in C++
Nilesh Dalvi
 
ARIES Recovery Algorithms
Pulasthi Lankeshwara
 
Python Basics
tusharpanda88
 
Functions in c
kalavathisugan
 
“An Introduction to Data Augmentation Techniques in ML Frameworks,” a Present...
Edge AI and Vision Alliance
 
C Programming Project
Vijayananda Mohire
 
Little o and little omega
Rajesh K Shukla
 
Mastering GC.pdf
Jean-Philippe BEMPEL
 
Data Augmentation
Md Tajul Islam
 
Matching networks for one shot learning
Kazuki Fujikawa
 

Viewers also liked (20)

PPSX
Introduction to .net framework
Arun Prasad
 
PPT
Architecture of .net framework
Then Murugeshwari
 
PPT
Architecture of net framework
umesh patil
 
PPTX
Prototype Pattern
Ider Zheng
 
PPTX
Builder pattern vs constructor
Liviu Tudor
 
PPTX
Input Output Management In C Programming
Kamal Acharya
 
PPTX
Desing pattern prototype-Factory Method, Prototype and Builder
paramisoft
 
PPTX
Asp Net Advance Topics
Ali Taki
 
PPTX
Database connectivity to sql server asp.net
Hemant Sankhla
 
PPTX
Managing input and output operation in c
yazad dumasia
 
PPTX
Basic Input and Output
Nurul Zakiah Zamri Tan
 
PPTX
ASP.NET State management
Shivanand Arur
 
PPT
Mesics lecture 5 input – output in ‘c’
eShikshak
 
PPT
Introduction to ADO.NET
rchakra
 
PPTX
Introduction to .NET Programming
Karthikeyan Mkr
 
PPTX
Introduction to .NET Framework and C# (English)
Vangos Pterneas
 
PPT
Introduction to .NET Framework
Raghuveer Guthikonda
 
PPT
.NET Framework Overview
Doncho Minkov
 
ODP
Prototype_pattern
Iryney Baran
 
PPTX
File management
Vishal Singh
 
Introduction to .net framework
Arun Prasad
 
Architecture of .net framework
Then Murugeshwari
 
Architecture of net framework
umesh patil
 
Prototype Pattern
Ider Zheng
 
Builder pattern vs constructor
Liviu Tudor
 
Input Output Management In C Programming
Kamal Acharya
 
Desing pattern prototype-Factory Method, Prototype and Builder
paramisoft
 
Asp Net Advance Topics
Ali Taki
 
Database connectivity to sql server asp.net
Hemant Sankhla
 
Managing input and output operation in c
yazad dumasia
 
Basic Input and Output
Nurul Zakiah Zamri Tan
 
ASP.NET State management
Shivanand Arur
 
Mesics lecture 5 input – output in ‘c’
eShikshak
 
Introduction to ADO.NET
rchakra
 
Introduction to .NET Programming
Karthikeyan Mkr
 
Introduction to .NET Framework and C# (English)
Vangos Pterneas
 
Introduction to .NET Framework
Raghuveer Guthikonda
 
.NET Framework Overview
Doncho Minkov
 
Prototype_pattern
Iryney Baran
 
File management
Vishal Singh
 
Ad

Similar to C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and Inheritance , Exploring the Base Class Library -, Debugging and Error Handling , Data Types (20)

PDF
LEARN C#
adroitinfogen
 
PPTX
Object oriented programming Fundamental Concepts
Bharat Kalia
 
PPT
Synapseindia dot net development
Synapseindiappsdevelopment
 
DOCX
C# Unit 2 notes
Sudarshan Dhondaley
 
PPT
Csharp_mahesh
Ananthu Mahesh
 
PPT
20 Object-oriented programming principles
maznabili
 
PPT
Dot Net csharp Language
Meetendra Singh
 
PPTX
C# - Igor Ralić
Software StartUp Academy Osijek
 
PPTX
5. c sharp language overview part ii
Svetlin Nakov
 
PPTX
C# overview part 2
sagaroceanic11
 
PPT
03 oo with-c-sharp
Naved khan
 
PPTX
csharp_dotnet_adnanreza.pptx
Poornima E.G.
 
PPT
C Language fundamentals hhhhhhhhhhhh.ppt
lalita57189
 
PPTX
.Net Framework 2 fundamentals
Harshana Weerasinghe
 
PPT
C#
Joni
 
PPT
Visula C# Programming Lecture 8
Abou Bakr Ashraf
 
PPT
Constructor
abhay singh
 
PPTX
Introduction to programming using c
Reham Maher El-Safarini
 
PDF
Intro to .NET and Core C#
Jussi Pohjolainen
 
DOCX
csharp.docx
LenchoMamudeBaro
 
LEARN C#
adroitinfogen
 
Object oriented programming Fundamental Concepts
Bharat Kalia
 
Synapseindia dot net development
Synapseindiappsdevelopment
 
C# Unit 2 notes
Sudarshan Dhondaley
 
Csharp_mahesh
Ananthu Mahesh
 
20 Object-oriented programming principles
maznabili
 
Dot Net csharp Language
Meetendra Singh
 
5. c sharp language overview part ii
Svetlin Nakov
 
C# overview part 2
sagaroceanic11
 
03 oo with-c-sharp
Naved khan
 
csharp_dotnet_adnanreza.pptx
Poornima E.G.
 
C Language fundamentals hhhhhhhhhhhh.ppt
lalita57189
 
.Net Framework 2 fundamentals
Harshana Weerasinghe
 
C#
Joni
 
Visula C# Programming Lecture 8
Abou Bakr Ashraf
 
Constructor
abhay singh
 
Introduction to programming using c
Reham Maher El-Safarini
 
Intro to .NET and Core C#
Jussi Pohjolainen
 
csharp.docx
LenchoMamudeBaro
 
Ad

More from yazad dumasia (7)

PPTX
Introduction to Pylab and Matploitlib.
yazad dumasia
 
PPTX
Schemas for multidimensional databases
yazad dumasia
 
PPTX
Classification decision tree
yazad dumasia
 
PPTX
Basic economic problem: Inflation
yazad dumasia
 
PPTX
Groundwater contamination
yazad dumasia
 
PPTX
Merge sort analysis and its real time applications
yazad dumasia
 
PPTX
Cyber crime
yazad dumasia
 
Introduction to Pylab and Matploitlib.
yazad dumasia
 
Schemas for multidimensional databases
yazad dumasia
 
Classification decision tree
yazad dumasia
 
Basic economic problem: Inflation
yazad dumasia
 
Groundwater contamination
yazad dumasia
 
Merge sort analysis and its real time applications
yazad dumasia
 
Cyber crime
yazad dumasia
 

Recently uploaded (20)

PPTX
Numerical-Solutions-of-Ordinary-Differential-Equations.pptx
SAMUKTHAARM
 
PDF
Electrical Machines and Their Protection.pdf
Nabajyoti Banik
 
PPTX
MODULE 03 - CLOUD COMPUTING AND SECURITY.pptx
Alvas Institute of Engineering and technology, Moodabidri
 
PPTX
Mechanical Design of shell and tube heat exchangers as per ASME Sec VIII Divi...
shahveer210504
 
PPTX
What is Shot Peening | Shot Peening is a Surface Treatment Process
Vibra Finish
 
PPTX
Water Resources Engineering (CVE 728)--Slide 3.pptx
mohammedado3
 
PDF
Pressure Measurement training for engineers and Technicians
AIESOLUTIONS
 
PDF
AI TECHNIQUES FOR IDENTIFYING ALTERATIONS IN THE HUMAN GUT MICROBIOME IN MULT...
vidyalalltv1
 
PPTX
Worm gear strength and wear calculation as per standard VB Bhandari Databook.
shahveer210504
 
PPTX
OCS353 DATA SCIENCE FUNDAMENTALS- Unit 1 Introduction to Data Science
A R SIVANESH M.E., (Ph.D)
 
PDF
Viol_Alessandro_Presentazione_prelaurea.pdf
dsecqyvhbowrzxshhf
 
PPTX
澳洲电子毕业证澳大利亚圣母大学水印成绩单UNDA学生证网上可查学历
Taqyea
 
PPTX
Knowledge Representation : Semantic Networks
Amity University, Patna
 
PPT
Testing and final inspection of a solar PV system
MuhammadSanni2
 
PDF
Digital water marking system project report
Kamal Acharya
 
PPTX
2025 CGI Congres - Surviving agile v05.pptx
Derk-Jan de Grood
 
PDF
AN EMPIRICAL STUDY ON THE USAGE OF SOCIAL MEDIA IN GERMAN B2C-ONLINE STORES
ijait
 
PDF
Reasons for the succes of MENARD PRESSUREMETER.pdf
majdiamz
 
PPTX
fatigue in aircraft structures-221113192308-0ad6dc8c.pptx
aviatecofficial
 
PDF
Basic_Concepts_in_Clinical_Biochemistry_2018كيمياء_عملي.pdf
AdelLoin
 
Numerical-Solutions-of-Ordinary-Differential-Equations.pptx
SAMUKTHAARM
 
Electrical Machines and Their Protection.pdf
Nabajyoti Banik
 
MODULE 03 - CLOUD COMPUTING AND SECURITY.pptx
Alvas Institute of Engineering and technology, Moodabidri
 
Mechanical Design of shell and tube heat exchangers as per ASME Sec VIII Divi...
shahveer210504
 
What is Shot Peening | Shot Peening is a Surface Treatment Process
Vibra Finish
 
Water Resources Engineering (CVE 728)--Slide 3.pptx
mohammedado3
 
Pressure Measurement training for engineers and Technicians
AIESOLUTIONS
 
AI TECHNIQUES FOR IDENTIFYING ALTERATIONS IN THE HUMAN GUT MICROBIOME IN MULT...
vidyalalltv1
 
Worm gear strength and wear calculation as per standard VB Bhandari Databook.
shahveer210504
 
OCS353 DATA SCIENCE FUNDAMENTALS- Unit 1 Introduction to Data Science
A R SIVANESH M.E., (Ph.D)
 
Viol_Alessandro_Presentazione_prelaurea.pdf
dsecqyvhbowrzxshhf
 
澳洲电子毕业证澳大利亚圣母大学水印成绩单UNDA学生证网上可查学历
Taqyea
 
Knowledge Representation : Semantic Networks
Amity University, Patna
 
Testing and final inspection of a solar PV system
MuhammadSanni2
 
Digital water marking system project report
Kamal Acharya
 
2025 CGI Congres - Surviving agile v05.pptx
Derk-Jan de Grood
 
AN EMPIRICAL STUDY ON THE USAGE OF SOCIAL MEDIA IN GERMAN B2C-ONLINE STORES
ijait
 
Reasons for the succes of MENARD PRESSUREMETER.pdf
majdiamz
 
fatigue in aircraft structures-221113192308-0ad6dc8c.pptx
aviatecofficial
 
Basic_Concepts_in_Clinical_Biochemistry_2018كيمياء_عملي.pdf
AdelLoin
 

C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and Inheritance , Exploring the Base Class Library -, Debugging and Error Handling , Data Types

  • 1. • Effort by : Name Enrollment no. • Dumasia Yazad H. 140420107015 • Gajjar Karan 140420107016 • Jinay Shah 140420107021 • Jay Pachchigar 140420107027 1 Computer (Shift-1) 6th year
  • 2. C# .NET LANGUAGE FEATURES AND CREATING .NET PROJECTS, NAMESPACES CLASSES AND INHERITANCE , EXPLORING THE BASE CLASS LIBRARY -, DEBUGGING AND ERROR HANDLING , DATA TYPES 2
  • 3. Some of the feature of Visual C# in .NET are: 1.Simple modern, Object Oriented Language 2.Aims to combine high productivity of Visual Basic and the raw power of C++. 3.Common Execution engine and rich class libraries 4.MS JVM equivalent is Common Language Run time(CLR) 5.CLR accommodates more then one language such C#,ASP,C++ etc 6.Source code Intermediate Language (IL) (JIT Compiler) Native code 7.Class and Data types are common to .NET Language 8.Develop Console applications, Windows applications & web app using C# 9.In C#, MS has taken care of C++ problem like memory management, pointers, etc. 10.It supports Garbage collection, Automatic memory management and a lot. Language Features And creating .NET project 3
  • 4. Language Features And creating .NET project Windows Store App Windows Client Office Enterprise WebsitesComponents Mobile Apps Backend Service 4
  • 5. Namespaces A namespace is designed for providing a way to keep one set of names separate from another. The class names declared in one namespace does not conflict with the same class names declared in another. 5
  • 6. using System; namespace first_space { class namespace_cl { public void func(){ Console.WriteLine("Inside first_space"); } } } namespace second_space { class namespace_cl { public void func() { Console.WriteLine("Inside second_space"); } } } class TestClass { staticc void Main(string[] args) { first_space.namespace_cl fc = new first_space.namespace_cl second_space.namespace_cl sc = new second_space.namespace_cl fc.func(); sc.func(); Console.ReadKey(); } } Inside first space Inside second space Output: Demonstrates use of namespaces: 6
  • 7. Class And Inheritance Classes in C# allow single inheritance and multiple interface inheritance. Each class can contain methods, properties, events, indexers, constants, constructors, destructors, operators and members can be static (can be accessed without an object instance) or instance member (require you to have a reference to an object first) Also, the access can be controlled in four different levels: public (everyone can access), protected (only inherited members can access), private (only members of the class can access) and internal (anyone on the same EXE or DLL can access) 7
  • 8. Example of Class public class Person{// Field public string name; // Constructor that takes no arguments. public Person(){ name = "unknown"; } // Constructor that takes one argument. public Person(string nm) { name = nm; } // Method public void SetName(string newName) { name = newName; } } class TestPerson { static void Main() { // Call the constructor that has no parameters. Person person1 = new Person(); Console.WriteLine(person1.name); person1.SetName(“Jinay Shah"); Console.WriteLine(person1.name); // Call the constructor that has one parameter. Person person2 = new Person(“Karan Gajjar"); Console.WriteLine(person2.name); Person person3 = new Person(“Jay Pachchigar"); Console.WriteLine(person2.name); Person person4 = new Person(“Yazad Dumasia"); Console.WriteLine(person2.name); // Keep the console window open in debug mode. Console.WriteLine("Press any key to exit."); Console.ReadKey(); } } Output: unknown Jinay Shah Karan Gajjar Jay Pachchigar Yazad Dumasia 8
  • 9. Inheritance is the ability to create a class from another class, the "parent" class, extending the functionality and state of the parent in the derived, or "child" class. It allows derived classes to overload methods from their parent class. Inheritance is one of the pillars of object-orientation. Important characteristics of inheritance include: 1. A derived class extends its base class. That is, it contains the methods and data of its parent class, and it can also contain its own data members and methods. 2. The derived class cannot change the definition of an inherited member. 3. Constructors and destructors are not inherited. All other members of the base class are inherited. 4. The accessibility of a member in the derived class depends upon its declared accessibility in the base class. 5. A derived class can override an inherited member. Class Inheritance 9
  • 10. C# does not support multiple inheritance. However, you can use interfaces to implement multiple inheritance. The following program demonstrates this: Multiple Inheritance in C# using System; namespace InheritanceApplication { class Shape { public void setWidth(int w) { width = w; } public void setHeight(int h) { height = h; } protected int width; protected int height; } // Base class PaintCost public interface PaintCost { int getCost(int area); } // Derived class class Rectangle : Shape, PaintCost { public int getArea() { return (width * height); } public int getCost(int area) { return area * 70; } } class RectangleTester { static void Main(string[] args) { Rectangle Rect = new Rectangle(); int area; Rect.setWidth(5); Rect.setHeight(7); area = Rect.getArea(); Console.WriteLine("Total area: {0}", Rect.getArea()); Console.WriteLine("Total paint cost: Rs {0}" , Rect.getCost(area)); Console.ReadKey(); } } } 10
  • 11. Use Base keyword in inheritance class A { int i; A(int n, int m) { x = n; y = m Console.WriteLine("n="+x+"m="+y); } } class B:A { int i; B(int a, int b):base(a,b)//calling base //class constructor and passing value { base.i = a;//passing value to base class field i = b; } public void Show() { Console.WriteLine("Derived class i="+i); Console.WriteLine("Base class i="+base.i); } } class MainClass { static void Main(string args [] ) { B b=new B(5,6);//passing value to derive class constructor b.Show(); } } OUTPUT n=5m=6 Derived class i=6 Base class i=5 11
  • 12. Exploring the Base Class Library Within the Microsoft .NET framework, there is a component known…as the base class library, And this is essentially library of classes, interfaces, and value types that you can. Use to provide common functionality in all of your .NET applications. The base class library is divided into namespaces to make locating that functionality easier. We've seen examples of using some of that functionality from the using directives that exist at the top of our Program.cs file.We bring in namespaces such as…System, and system.Collections.Generic, System.Text, and System.Threading.Tasks. 12
  • 13. Exploring the Base Class Library And within these namespaces exist classes that perform certain functionality that are related to the namespaces. As an example, let's take a look at what…exists in the System.Text namespace for functionality or for classes. Now in order to do that, one of the…simplest ways is to bring up our Object Browser window.…If we click on the View menu, we can see that there's…a window called Object Browser, and the shortcut key combination is Ctrl+ALT+J. 13
  • 14. Exception Handling An exception is a problem that arises during the execution of a program. C# exception handling is built upon four keywords: o Try: A try block identifies a block of code for which particular exceptions will be activated. It's followed by one or more catch blocks. o Catch: A program catches an exception with an exception handler at the place in a program where you want to handle the problem. The catch keyword indicates the catching of an exception. o Finally: The finally block is used to execute a given set of statements, whether an exception is thrown or not thrown. For example, if you open a file, it must be closed whether an exception is raised or not. o Throw: A program throws an exception when a problem shows up. This is done using a throw keyword. 14
  • 16. C# exceptions are represented by classes. The exception classes in C# are mainly directly or indirectly derived from the System.Exception class. Some of the exception classes derived from the System. Exception class are the System.ApplicationException and System.SystemException classes 16
  • 17. class Program { public static void division(int num1, int num2) { float result=0.0f; try { result = num1 / num2; } catch (DivideByZeroException e) { Console.WriteLine("Exception Error !! n divid by zero !!"); // Console.WriteLine("Exception caught: {0}", e); } finally { Console.WriteLine("Result: {0} ", result); } } static void Main(string[] args) { division(10,0); Console.ReadLine(); } } 17
  • 18. User Defined Exception using System; namespace ExceptionHandling { class NegativeNumberException:ApplicationException { public NegativeNumberException(string message) // show message } } if(value<0) throw new NegativeNumberException(" Use Only Positive numbers"); 18
  • 19. THE COMMON TYPE SYSTEM (CTS) String Array ValueType Exception Delegate Class1 Multicast Delegate Class2 Class3 Object Enum1 Structure1Enum Primitive types Boolean Byte Int16 Int32 Int64 Char Single Double Decimal DateTime System-defined types User-defined types Delegate1 TimeSpan Guid 19
  • 20. Not all languages support all CTS types and features C# supports unsigned integer types, VB.NET does not C# is case sensitive, VB.NET is not C# supports pointer types (in unsafe mode), VB.NET does not C# supports operator overloading, VB.NET does not CLS was drafted to promote language interoperability vast majority of classes within FCL are CLS-compliant 20
  • 21. MAPPING C# TO CTSLanguage keywords map to common CTS classes: Keyword Description Special format for literals bool Boolean true false char 16 bit Unicode character 'A' 'x0041' 'u0041' sbyte 8 bit signed integer none byte 8 bit unsigned integer none short 16 bit signed integer none ushort 16 bit unsigned integer none int 32 bit signed integer none uint 32 bit unsigned integer U suffix long 64 bit signed integer L or l suffix ulong 64 bit unsigned integer U/u and L/l suffix float 32 bit floating point F or f suffix double 64 bit floating point no suffix decimal 128 bit high precision M or m suffix string character sequence "hello", @"C:dirfile.txt" 21
  • 22. EXAMPLE • An example of using types in C# • declare before you use (compiler enforced) • initialize before you use (compiler enforced) public class App { public static void Main() { int width, height; width = 2; height = 4; int area = width * height; int x; int y = x * 2; ... } } declarations decl + initializer error, x not set 22
  • 23. BOXING AND UNBOXING • When necessary, C# will auto-convert value <==> object • value ==> object is called "boxing" • object ==> value is called "unboxing" int i, j; object obj; string s; i = 32; obj = i; // boxed copy! i = 19; j = (int) obj; // unboxed! s = j.ToString(); // boxed! s = 99.ToString(); // boxed! 23
  • 24. USER-DEFINED REFERENCE TYPES• Classes! • for example, Customer class we worked with earlier… public class Customer { public string Name; // fields public int ID; public Customer(string name, int id) // constructor { this.Name = name; this.ID = id; } public override string ToString() // method { return "Customer: " + this.Name; } } 24
  • 25. 25