Click here to Skip to main content
15,900,973 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have 2 classes, Animal and dog. dog inherits from Animal class. How come i am not able to access the field b with dog.b ? If dog inherits from Animal , then should it know about b ?


C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace inheritance1
{
    class Program
    {
        static void Main(string[] args)
        {



            Animal a = new Animal();

            a.b = 5;

            Console.WriteLine(a.b);



            dog d = new dog();

            dog.b = 4;

            Console.WriteLine(dog.b);

            Console.ReadKey();


        }
    }


    class Animal
    {
        public int b = 3;
    
    }

    class dog : Animal
    { 
    }




}


What I have tried:

dog.b = 4;
Posted
Updated 4-Nov-16 13:54pm
v2

1 solution

You can access the b field using the dog instance, but the problem here is you are using class name directly instead of instance variable, you need to call it using d like :

C#
dog d = new dog();

d.b = 4; // note this, use instance variable not class name
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900