SlideShare une entreprise Scribd logo
1  sur  9
Télécharger pour lire hors ligne
:C#Notes
Week 5(according to IUB outline):-
---------------------------------------------------------------------------------
Implementing Object-Oriented Programming Techniques in C# Part-I
1. Designing Objects: Use of this keyword
2. Using Encapsulation: Creating Properties
3. Using Inheritance: Parent and Child classes
4. Use of super keyword
5. Concepts of Generalization and Specialization.
---------------------------------------------------------------------------------
Any issue:umarfarooqworld@outlook.com
umarfarooqworld@gmail.com
MCS(3rd
semester)
NICE College Rahim Yar Khan
Ref: C#Corner Pick “N” Share :C#Notes
2 | P a g e “A room without books is like a body without a soul”
1.This keyword (current reference)
The keyword "this" in C# is used to access the field variables. All the field variables must be
accessed using "this" keyword. It is useful when the field variable and the local variables of
a method have same name. In the above case local variables overrides field variables and
field variables are no more visible inside the method. So this can be used to refer field
variables to make visible inside method.
1.1. Example
1. using System;
2. using System.Collections.Generic;
3. using System.Linq;
4. using System.Text;
5. namespace Read_and_Write_Property
6. {
7. class Demo
8. {
9. int a=2,b=10;
10. public void get()
11. {
12. int a=23,b=34;
13. Console.WriteLine("a={0} b={1}",this.a,this.b);
14. Console.WriteLine(“it is the class variable”);
15. Console.WriteLine(“Now the local variables are”);
16. Console.WriteLine(a={0} b={1},a,b);
17. }
18. }
19. class MainClass
20. {
21. static void Main(string args[])
22. Demo d=new Demo();
23. d.get();
24. }
25. }
a=2 b=10
It is the class variable
Now the local variables are:
a=23 b=34
Output:
Ref: C#Corner Pick “N” Share :C#Notes
3 | P a g e “A room without books is like a body without a soul”
2.Properties
In C#, properties are a member that provides a flexible mechanism to read, write, or compute the
value of a private field. C# is one of the first languages that offers direct support of
Properties. Properties looks similar to a public variable on which we can do get() or set()
operations. This method is also known as Encapsulation.
Syntax
The following is the syntax of Properties:
1. Public string MyName //property-Access-modifier(public), Property-
type(string) and property-name(MyName).
2. {
3. get
4. {
5. return name;
6. }
7. set
8. {
9. name=value; //Automatically value sets to variable name.
10. }
11.}
In the syntax shown above:
1. The access modifier can be Private, Public, Protected or Internal.
2. The return type can be any valid C# data type, such as a string or integer.
3. The ”this” keyword shows that the object is for the current class.
4. The get() and set() operations of the syntax are known as accessors.
2.1 Read and write Property
Programmers allow you to access the internal data of a class in a less cumbersome
manner. Earlier programmers were required to define two separate methods, one for
assigning a value of a variable and the other for retrieving the value of a variable. When
you create a property, the compiler automatically generates class methods to set() and
get() the property value and makes calls to these methods automatically when a
programmer uses the property.
Ref: C#Corner Pick “N” Share :C#Notes
4 | P a g e “A room without books is like a body without a soul”
Figure 1: Read and write property
26.using System;
27.using System.Collections.Generic;
28.using System.Linq;
29.using System.Text;
30.namespace Read_and_Write_Property
31.{
32. class student
33. {
34. public string Myname;
35. public int Myage;
36. public student
37. {
38. Myname= "";
39. Myage = 0;
40. }
41. public string Name //Declare a Name Property of type String
42. {
43. get {return Myname; }
44. set { Myname = value;}
45. }
46. public int Age //Declare an Age Property of type int
47. {
48. get {return Myage ;}
49. set {Myage = value;}
50. }
51. }
52. class Program
53. {
54. static void Main(string[] args)
55. {
56. Console.WriteLine("This is Read and Write Propety");
// Create a new object for student class
57. student s = new student();
58. Console.WriteLine("Name={0} and Age={1}”,s.Name,s.Age);
59. s.Name = "Pick n share"; //set Name via property
60. s.Age = 24; //set Age via property
61. Console.WriteLine("Name={0} and Age={1}”,s.Name,s.Age);
62. s.Age += 1; //increment the age property
63. Console.Write("Name={0} and Age={1}”,s.Name,s.Age);
64. Console.ReadKey();
65. }
66. }
67.}
Output:
Ref: C#Corner Pick “N” Share :C#Notes
2.2 Read-Only Property
A read-only Property has a get accessor but does not have any set() operation. This
means that you can retrieve the value of a variable using the read-only property but you
cannot assign a value to the variable.
Here is the Code
Figure 2: Read-only property
1. using System;
2. using System.Collections.Generic;
3. using System.Linq;
4. using System.Text;
5. namespace ConsoleApplication1
6. {
7. public class PropertyHolder
8. {
9. private int Myage = 0;
10. public PropertyHolder(int PropVal)
11. {
12. Myage = PropVal;
13. }
14. public int age
15. {
16. get {
17. return Myage;
18. }
19. }
20. }
21.
22. class Program
23. {
24. static void Main(string[] args)
25. {
26. PropertyHolder p = new PropertyHolder(24);
27. Console.WriteLine("My age is: " + p.age);
28. Console.ReadKey();
29. }
30. }
31.}
Output:
Ref: C#Corner Pick “N” Share :C#Notes
6 | P a g e “A room without books is like a body without a soul”
3. Inheritance Introduction
3.1 Real-world Example
A scientific calculator is an extended form of a calculator. Here calculator is the parent
and scientific calculator is child object.
3.2 Programming Example
The process of acquiring the existing functionality of the parent and with the new added
features and functionality of a child object.
3.3 What Inheritance is
Inheritance is one of the three foundational principles of Object-Oriented Programming
(OOP) because it allows the creation of hierarchical classifications. Using inheritance
you can create a general class that defines traits common to a set of related items. This
class can then be inherited by other, more specific classes, each adding those things
that are unique to it.
In the language of C#, a class that is inherited is called a base class. The class that
does the inheriting is called the derived class. Therefore a derived class is a specialized
version of a base class. It inherits all of the variables, methods, properties, and indexers
defined by the base class and add its own unique elements.
3.4 Example
Diagram
The following diagram shows the inheritance of a shape class. Here the base class is
Shape and the other classes are its child classes. In the following program we will
explain the inheritance of the Triangle class from the Shape class.
Ref: C#Corner Pick “N” Share :C#Notes
7 | P a g e “A room without books is like a body without a soul”
3.5 Programming Example
1. //Base class or Parent class.
2. class Shape
3. {
4. public double Width;
5. public double Height;
6. public void ShowDim()
7. {
8. Console.WriteLine("Width and height are " +
9. Width + " and " + Height);
10. }
11.}
12.// Triangle is derived from Shape.
13.//Drived class or Child class.
14.class Triangle : Shape
15.{
16. public string Style; // style of triangle
17. // Return area of triangle.
18. public double Area()
19. {
20. return Width * Height / 2;
21. }
22. // Display a triangle's style.
23. public void ShowStyle()
24. {
25. Console.WriteLine("Triangle is " + Style);
26. }
27.}
28.//Driver class which runs the program.
29.class Driver
30.{
31. static void Main()
32. {
33. Triangle t1 new Triangle();
34. Triangle t2 new Triangle();
35. t1.Width =4.0;
36. t1.Height =4.0;
37. t1.Style ="isosceles";
38. t2.Width =8.0;
39. t2.Height =12.0;
40. t2.Style ="right";
41. Console.WriteLine("Info for t1: ");
42. t1.ShowStyle();
43. t1.ShowDim();
44. Console.WriteLine("Area is " + t1.Area());
45. Console.WriteLine();
46. Console.WriteLine("Info for t2: ");
47. t2.ShowStyle();
48. t2.ShowDim();
49. Console.WriteLine("Area is " + t2.Area());
50. }
51.}
The output from this
program is shown here:
Info for t1:
Triangle is isosceles
Width and height are 4 and 4
Area is 8
Info for t2:
Triangle is right
Width and height are 8 and 12
Area is 48
Ref: C#Corner Pick “N” Share :C#Notes
8 | P a g e “A room without books is like a body without a soul”
4.Base Keyword
The concept of base keyword is very simple in c#. The base keyword is used when we want to
access members and functionalities of the base class, from within a derived class. In the following
example, both the base class, Owner, and the derived class, Employee, have a method named info.
By using the base keyword, it is possible to call the info method on the base class, from within the
derived class.
4.1 Example
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace this_example
{
public class Owner
{
protected string pin = "78";
protected string name = "zubair";
public virtual void Info()
{
Console.WriteLine("Name: {0}", name);
Console.WriteLine("pin: {0}", pin);
}
}
class Employee : Owner
{
public string id = "ABC567";
public override void Info()
{
// Calling the base class GetInfo method:
base.Info();
Console.WriteLine("Employee ID: {0}", id);
}
}
class TestClass
{
public static void Main()
{
Employee E = new Employee();
E.Info();
Console.ReadLine();
}
}
}
The output from this
program is shown here:
Name: zubair
Pin: 78
Employee ID: ABC567
Ref: C#Corner Pick “N” Share :C#Notes
9 | P a g e “A room without books is like a body without a soul”
4.2 base (C# Reference)
The base keyword is used to access members of the base class from within a derived class:1
i. Call a method on the base class that has been overridden by another method.
ii. Specify which base-class constructor should be called when creating instances of
the derived class.
A base class access is permitted only in a constructor, an instance method, or an instance
property accessor.
It is an error to use the base keyword from within a static method.
The base class that is accessed is the base class specified in the class declaration. For
example, if you specify class ClassB : ClassA , the members of ClassA are accessed from
ClassB, regardless of the base class of ClassA.
5.Generalization and Specialization
The process of extracting common characteristics from two or more classes and combining
them into a generalized superclass, is called Generalization. The common characteristics can
be attributes or methods. Generalization is represented by a triangle followed by a line.
Specialization is the reverse process of Generalization means creating new sub classes from
an existing class.
Let’s take an example of Bank Account; A Bank Account is of two types – Current Account
and Saving Account. Current Account and Saving Account inherits the common/
generalized properties like Account Number, Account Balance etc. from a Bank Account and
also have their own specialized properties like interest rate etc.
Note:
One thing! Keep in your mind, Base keyword is used in c# instead of Super
keyword.

Contenu connexe

Tendances

Tendances (20)

C++ Inheritance
C++ InheritanceC++ Inheritance
C++ Inheritance
 
Ch.1 oop introduction, classes and objects
Ch.1 oop introduction, classes and objectsCh.1 oop introduction, classes and objects
Ch.1 oop introduction, classes and objects
 
iOS 101 - Xcode, Objective-C, iOS APIs
iOS 101 - Xcode, Objective-C, iOS APIsiOS 101 - Xcode, Objective-C, iOS APIs
iOS 101 - Xcode, Objective-C, iOS APIs
 
Object Oriented Programming With C++
Object Oriented Programming With C++Object Oriented Programming With C++
Object Oriented Programming With C++
 
Learning C++ - Class 4
Learning C++ - Class 4Learning C++ - Class 4
Learning C++ - Class 4
 
Objective-C for iOS Application Development
Objective-C for iOS Application DevelopmentObjective-C for iOS Application Development
Objective-C for iOS Application Development
 
Introduction to Objective - C
Introduction to Objective - CIntroduction to Objective - C
Introduction to Objective - C
 
Object oriented programming in C++
Object oriented programming in C++Object oriented programming in C++
Object oriented programming in C++
 
Inheritance
InheritanceInheritance
Inheritance
 
Learn Concept of Class and Object in C# Part 3
Learn Concept of Class and Object in C#  Part 3Learn Concept of Class and Object in C#  Part 3
Learn Concept of Class and Object in C# Part 3
 
Intake 38 5
Intake 38 5Intake 38 5
Intake 38 5
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
 
Chapter 05 classes and objects
Chapter 05 classes and objectsChapter 05 classes and objects
Chapter 05 classes and objects
 
Inheritance
InheritanceInheritance
Inheritance
 
Inheritance, polymorphisam, abstract classes and composition)
Inheritance, polymorphisam, abstract classes and composition)Inheritance, polymorphisam, abstract classes and composition)
Inheritance, polymorphisam, abstract classes and composition)
 
14 Defining Classes
14 Defining Classes14 Defining Classes
14 Defining Classes
 
2CPP14 - Abstraction
2CPP14 - Abstraction2CPP14 - Abstraction
2CPP14 - Abstraction
 
Constructor
ConstructorConstructor
Constructor
 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructors
 
The Ring programming language version 1.2 book - Part 78 of 84
The Ring programming language version 1.2 book - Part 78 of 84The Ring programming language version 1.2 book - Part 78 of 84
The Ring programming language version 1.2 book - Part 78 of 84
 

Similaire à C# (This keyword, Properties, Inheritance, Base Keyword)

classes object fgfhdfgfdgfgfgfgfdoop.pptx
classes object  fgfhdfgfdgfgfgfgfdoop.pptxclasses object  fgfhdfgfdgfgfgfgfdoop.pptx
classes object fgfhdfgfdgfgfgfgfdoop.pptx
arjun431527
 
Oop lec 4(oop design, style, characteristics)
Oop lec 4(oop design, style, characteristics)Oop lec 4(oop design, style, characteristics)
Oop lec 4(oop design, style, characteristics)
Asfand Hassan
 
Object-Oriented Programming with C#
Object-Oriented Programming with C#Object-Oriented Programming with C#
Object-Oriented Programming with C#
Svetlin Nakov
 
I assignmnt(oops)
I assignmnt(oops)I assignmnt(oops)
I assignmnt(oops)
Jay Patel
 
C Sharp: Basic to Intermediate Part 01
C Sharp: Basic to Intermediate Part 01C Sharp: Basic to Intermediate Part 01
C Sharp: Basic to Intermediate Part 01
Zafor Iqbal
 

Similaire à C# (This keyword, Properties, Inheritance, Base Keyword) (20)

Polymorphism, Abstarct Class and Interface in C#
Polymorphism, Abstarct Class and Interface in C#Polymorphism, Abstarct Class and Interface in C#
Polymorphism, Abstarct Class and Interface in C#
 
classes object fgfhdfgfdgfgfgfgfdoop.pptx
classes object  fgfhdfgfdgfgfgfgfdoop.pptxclasses object  fgfhdfgfdgfgfgfgfdoop.pptx
classes object fgfhdfgfdgfgfgfgfdoop.pptx
 
Oop lec 4(oop design, style, characteristics)
Oop lec 4(oop design, style, characteristics)Oop lec 4(oop design, style, characteristics)
Oop lec 4(oop design, style, characteristics)
 
Object-Oriented Programming with C#
Object-Oriented Programming with C#Object-Oriented Programming with C#
Object-Oriented Programming with C#
 
Introduction to object oriented programming concepts
Introduction to object oriented programming conceptsIntroduction to object oriented programming concepts
Introduction to object oriented programming concepts
 
C# classes objects
C#  classes objectsC#  classes objects
C# classes objects
 
Properties and Indexers
Properties and IndexersProperties and Indexers
Properties and Indexers
 
Ppt of c++ vs c#
Ppt of c++ vs c#Ppt of c++ vs c#
Ppt of c++ vs c#
 
Oops concept on c#
Oops concept on c#Oops concept on c#
Oops concept on c#
 
I assignmnt(oops)
I assignmnt(oops)I assignmnt(oops)
I assignmnt(oops)
 
Object-oriented programming (OOP) with Complete understanding modules
Object-oriented programming (OOP) with Complete understanding modulesObject-oriented programming (OOP) with Complete understanding modules
Object-oriented programming (OOP) with Complete understanding modules
 
Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programming
 
C# Unit 2 notes
C# Unit 2 notesC# Unit 2 notes
C# Unit 2 notes
 
constructors.pptx
constructors.pptxconstructors.pptx
constructors.pptx
 
Bca 2nd sem u-2 classes & objects
Bca 2nd sem u-2 classes & objectsBca 2nd sem u-2 classes & objects
Bca 2nd sem u-2 classes & objects
 
Java Programming - 04 object oriented in java
Java Programming - 04 object oriented in javaJava Programming - 04 object oriented in java
Java Programming - 04 object oriented in java
 
Php oop (1)
Php oop (1)Php oop (1)
Php oop (1)
 
Class and object in C++ By Pawan Thakur
Class and object in C++ By Pawan ThakurClass and object in C++ By Pawan Thakur
Class and object in C++ By Pawan Thakur
 
Object & classes
Object & classes Object & classes
Object & classes
 
C Sharp: Basic to Intermediate Part 01
C Sharp: Basic to Intermediate Part 01C Sharp: Basic to Intermediate Part 01
C Sharp: Basic to Intermediate Part 01
 

Plus de Umar Farooq

Plus de Umar Farooq (9)

Ado.Net Architecture
Ado.Net ArchitectureAdo.Net Architecture
Ado.Net Architecture
 
Linq in C#
Linq in C#Linq in C#
Linq in C#
 
Creating Windows-based Applications Part-I
Creating Windows-based Applications Part-ICreating Windows-based Applications Part-I
Creating Windows-based Applications Part-I
 
Building .NET-based Applications with C#
Building .NET-based Applications with C#Building .NET-based Applications with C#
Building .NET-based Applications with C#
 
Selection Sort
Selection Sort Selection Sort
Selection Sort
 
Week 9 IUB c#
Week 9 IUB c#Week 9 IUB c#
Week 9 IUB c#
 
Matrix
MatrixMatrix
Matrix
 
Array and Collections in c#
Array and Collections in c#Array and Collections in c#
Array and Collections in c#
 
Software process model
Software process modelSoftware process model
Software process model
 

Dernier

Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
KarakKing
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
ZurliaSoop
 

Dernier (20)

How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 

C# (This keyword, Properties, Inheritance, Base Keyword)

  • 1. :C#Notes Week 5(according to IUB outline):- --------------------------------------------------------------------------------- Implementing Object-Oriented Programming Techniques in C# Part-I 1. Designing Objects: Use of this keyword 2. Using Encapsulation: Creating Properties 3. Using Inheritance: Parent and Child classes 4. Use of super keyword 5. Concepts of Generalization and Specialization. --------------------------------------------------------------------------------- Any issue:umarfarooqworld@outlook.com umarfarooqworld@gmail.com MCS(3rd semester) NICE College Rahim Yar Khan
  • 2. Ref: C#Corner Pick “N” Share :C#Notes 2 | P a g e “A room without books is like a body without a soul” 1.This keyword (current reference) The keyword "this" in C# is used to access the field variables. All the field variables must be accessed using "this" keyword. It is useful when the field variable and the local variables of a method have same name. In the above case local variables overrides field variables and field variables are no more visible inside the method. So this can be used to refer field variables to make visible inside method. 1.1. Example 1. using System; 2. using System.Collections.Generic; 3. using System.Linq; 4. using System.Text; 5. namespace Read_and_Write_Property 6. { 7. class Demo 8. { 9. int a=2,b=10; 10. public void get() 11. { 12. int a=23,b=34; 13. Console.WriteLine("a={0} b={1}",this.a,this.b); 14. Console.WriteLine(“it is the class variable”); 15. Console.WriteLine(“Now the local variables are”); 16. Console.WriteLine(a={0} b={1},a,b); 17. } 18. } 19. class MainClass 20. { 21. static void Main(string args[]) 22. Demo d=new Demo(); 23. d.get(); 24. } 25. } a=2 b=10 It is the class variable Now the local variables are: a=23 b=34 Output:
  • 3. Ref: C#Corner Pick “N” Share :C#Notes 3 | P a g e “A room without books is like a body without a soul” 2.Properties In C#, properties are a member that provides a flexible mechanism to read, write, or compute the value of a private field. C# is one of the first languages that offers direct support of Properties. Properties looks similar to a public variable on which we can do get() or set() operations. This method is also known as Encapsulation. Syntax The following is the syntax of Properties: 1. Public string MyName //property-Access-modifier(public), Property- type(string) and property-name(MyName). 2. { 3. get 4. { 5. return name; 6. } 7. set 8. { 9. name=value; //Automatically value sets to variable name. 10. } 11.} In the syntax shown above: 1. The access modifier can be Private, Public, Protected or Internal. 2. The return type can be any valid C# data type, such as a string or integer. 3. The ”this” keyword shows that the object is for the current class. 4. The get() and set() operations of the syntax are known as accessors. 2.1 Read and write Property Programmers allow you to access the internal data of a class in a less cumbersome manner. Earlier programmers were required to define two separate methods, one for assigning a value of a variable and the other for retrieving the value of a variable. When you create a property, the compiler automatically generates class methods to set() and get() the property value and makes calls to these methods automatically when a programmer uses the property.
  • 4. Ref: C#Corner Pick “N” Share :C#Notes 4 | P a g e “A room without books is like a body without a soul” Figure 1: Read and write property 26.using System; 27.using System.Collections.Generic; 28.using System.Linq; 29.using System.Text; 30.namespace Read_and_Write_Property 31.{ 32. class student 33. { 34. public string Myname; 35. public int Myage; 36. public student 37. { 38. Myname= ""; 39. Myage = 0; 40. } 41. public string Name //Declare a Name Property of type String 42. { 43. get {return Myname; } 44. set { Myname = value;} 45. } 46. public int Age //Declare an Age Property of type int 47. { 48. get {return Myage ;} 49. set {Myage = value;} 50. } 51. } 52. class Program 53. { 54. static void Main(string[] args) 55. { 56. Console.WriteLine("This is Read and Write Propety"); // Create a new object for student class 57. student s = new student(); 58. Console.WriteLine("Name={0} and Age={1}”,s.Name,s.Age); 59. s.Name = "Pick n share"; //set Name via property 60. s.Age = 24; //set Age via property 61. Console.WriteLine("Name={0} and Age={1}”,s.Name,s.Age); 62. s.Age += 1; //increment the age property 63. Console.Write("Name={0} and Age={1}”,s.Name,s.Age); 64. Console.ReadKey(); 65. } 66. } 67.} Output:
  • 5. Ref: C#Corner Pick “N” Share :C#Notes 2.2 Read-Only Property A read-only Property has a get accessor but does not have any set() operation. This means that you can retrieve the value of a variable using the read-only property but you cannot assign a value to the variable. Here is the Code Figure 2: Read-only property 1. using System; 2. using System.Collections.Generic; 3. using System.Linq; 4. using System.Text; 5. namespace ConsoleApplication1 6. { 7. public class PropertyHolder 8. { 9. private int Myage = 0; 10. public PropertyHolder(int PropVal) 11. { 12. Myage = PropVal; 13. } 14. public int age 15. { 16. get { 17. return Myage; 18. } 19. } 20. } 21. 22. class Program 23. { 24. static void Main(string[] args) 25. { 26. PropertyHolder p = new PropertyHolder(24); 27. Console.WriteLine("My age is: " + p.age); 28. Console.ReadKey(); 29. } 30. } 31.} Output:
  • 6. Ref: C#Corner Pick “N” Share :C#Notes 6 | P a g e “A room without books is like a body without a soul” 3. Inheritance Introduction 3.1 Real-world Example A scientific calculator is an extended form of a calculator. Here calculator is the parent and scientific calculator is child object. 3.2 Programming Example The process of acquiring the existing functionality of the parent and with the new added features and functionality of a child object. 3.3 What Inheritance is Inheritance is one of the three foundational principles of Object-Oriented Programming (OOP) because it allows the creation of hierarchical classifications. Using inheritance you can create a general class that defines traits common to a set of related items. This class can then be inherited by other, more specific classes, each adding those things that are unique to it. In the language of C#, a class that is inherited is called a base class. The class that does the inheriting is called the derived class. Therefore a derived class is a specialized version of a base class. It inherits all of the variables, methods, properties, and indexers defined by the base class and add its own unique elements. 3.4 Example Diagram The following diagram shows the inheritance of a shape class. Here the base class is Shape and the other classes are its child classes. In the following program we will explain the inheritance of the Triangle class from the Shape class.
  • 7. Ref: C#Corner Pick “N” Share :C#Notes 7 | P a g e “A room without books is like a body without a soul” 3.5 Programming Example 1. //Base class or Parent class. 2. class Shape 3. { 4. public double Width; 5. public double Height; 6. public void ShowDim() 7. { 8. Console.WriteLine("Width and height are " + 9. Width + " and " + Height); 10. } 11.} 12.// Triangle is derived from Shape. 13.//Drived class or Child class. 14.class Triangle : Shape 15.{ 16. public string Style; // style of triangle 17. // Return area of triangle. 18. public double Area() 19. { 20. return Width * Height / 2; 21. } 22. // Display a triangle's style. 23. public void ShowStyle() 24. { 25. Console.WriteLine("Triangle is " + Style); 26. } 27.} 28.//Driver class which runs the program. 29.class Driver 30.{ 31. static void Main() 32. { 33. Triangle t1 new Triangle(); 34. Triangle t2 new Triangle(); 35. t1.Width =4.0; 36. t1.Height =4.0; 37. t1.Style ="isosceles"; 38. t2.Width =8.0; 39. t2.Height =12.0; 40. t2.Style ="right"; 41. Console.WriteLine("Info for t1: "); 42. t1.ShowStyle(); 43. t1.ShowDim(); 44. Console.WriteLine("Area is " + t1.Area()); 45. Console.WriteLine(); 46. Console.WriteLine("Info for t2: "); 47. t2.ShowStyle(); 48. t2.ShowDim(); 49. Console.WriteLine("Area is " + t2.Area()); 50. } 51.} The output from this program is shown here: Info for t1: Triangle is isosceles Width and height are 4 and 4 Area is 8 Info for t2: Triangle is right Width and height are 8 and 12 Area is 48
  • 8. Ref: C#Corner Pick “N” Share :C#Notes 8 | P a g e “A room without books is like a body without a soul” 4.Base Keyword The concept of base keyword is very simple in c#. The base keyword is used when we want to access members and functionalities of the base class, from within a derived class. In the following example, both the base class, Owner, and the derived class, Employee, have a method named info. By using the base keyword, it is possible to call the info method on the base class, from within the derived class. 4.1 Example using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace this_example { public class Owner { protected string pin = "78"; protected string name = "zubair"; public virtual void Info() { Console.WriteLine("Name: {0}", name); Console.WriteLine("pin: {0}", pin); } } class Employee : Owner { public string id = "ABC567"; public override void Info() { // Calling the base class GetInfo method: base.Info(); Console.WriteLine("Employee ID: {0}", id); } } class TestClass { public static void Main() { Employee E = new Employee(); E.Info(); Console.ReadLine(); } } } The output from this program is shown here: Name: zubair Pin: 78 Employee ID: ABC567
  • 9. Ref: C#Corner Pick “N” Share :C#Notes 9 | P a g e “A room without books is like a body without a soul” 4.2 base (C# Reference) The base keyword is used to access members of the base class from within a derived class:1 i. Call a method on the base class that has been overridden by another method. ii. Specify which base-class constructor should be called when creating instances of the derived class. A base class access is permitted only in a constructor, an instance method, or an instance property accessor. It is an error to use the base keyword from within a static method. The base class that is accessed is the base class specified in the class declaration. For example, if you specify class ClassB : ClassA , the members of ClassA are accessed from ClassB, regardless of the base class of ClassA. 5.Generalization and Specialization The process of extracting common characteristics from two or more classes and combining them into a generalized superclass, is called Generalization. The common characteristics can be attributes or methods. Generalization is represented by a triangle followed by a line. Specialization is the reverse process of Generalization means creating new sub classes from an existing class. Let’s take an example of Bank Account; A Bank Account is of two types – Current Account and Saving Account. Current Account and Saving Account inherits the common/ generalized properties like Account Number, Account Balance etc. from a Bank Account and also have their own specialized properties like interest rate etc. Note: One thing! Keep in your mind, Base keyword is used in c# instead of Super keyword.