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.