C# Parent Child Reference Variable & Object Casting

I have been clearing my concepts regarding inheritance and investigating if parent reference variable can point to child class object and vice versa.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
    using System;
    using System.Collections.Generic;
    using System.Text;

    namespace oops
    {
    public class A
    {
    public A()
    {
    Console.WriteLine("A");
    Console.WriteLine("===============================");
    }
    public void Add()
    {
    Console.WriteLine("Add");
    }
    }

    public class B : A
    {
    public B()
    {
    Console.WriteLine("B");
    Console.WriteLine("===============================");
    }

    public void Sub()
    {
    Console.WriteLine("Sub");
    }

    }

    class Program
    {
    static void Main(string[] args)
    {
    A objA = new A();

    B objB = objA as B;
    A objAB = new B();

    B objBB = objAB as B;
    objBB.Sub();

    if (objB is B)
    {
    objB.Add();
    }
    else
    {
    Console.WriteLine("objB is not B");
    }

    //objA.Add();
    Console.ReadLine();
    }
    }
    }

Out put of the code is

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
    A
    ===============================
    A
    ===============================

    B
    ===============================

    Sub

    objB is not B
comments powered by Disqus