1

Program

using System;

namespace ConsoleApp4
{
    class Program
    {
        static void Main(string[] args)
        {
            B x = new B();
            x.show();
        }
    }

    public class A     //base class
    {
        protected int no = 1;

        public void show()
        {
            Console.WriteLine(no);
        }
    }
    public class B : A  //sub class
    {
        protected int no = 100;
    }
}

Output 1

How do I use sub Class attribute value instead of base class attribute value?

I tried override, new keywords and it doesn't seem to work.

What I have learned regarding this question is: sub class holds both parent class attribute, and its own attribute.

But sub class attribute get hide by base class attribute, if it is intentional you can use new keyword.

Thank you

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

2 Answers2

3

how to Use sub class attriubute in C#

protected int no = 1;

This is not an attribute, it's a field.

You can either reassign that field's value in the subclass (fiddle):

public class B : A  //sub class
{
    public B() 
    {
        no = 100; 
    }
}

Or you can replace your field with a property, which can be virtual and, thus, overridden (fiddle):

public class A     //base class
{
    protected virtual int no => 1;

    public void show()
    {
        Console.WriteLine(no);
    }
}
public class B : A  //sub class
{
    protected override int no => 100;
}
Heinzi
  • 167,459
  • 57
  • 363
  • 519
1

Do not declare no field in class B. You can access no from contructor or method.

By declaring no in class B you are hiding no in class A. I suggest not to use same names for fields in inherited classs. By using protected you can access no field from both classes.

public class A     //base class
{
    protected int no = 1;

    public void show()
    {
        Console.WriteLine(no);
    }
}
public class B : A  //sub class
{
    public B()
    {
        no = 2;
    }
}
Vít Bednář
  • 288
  • 2
  • 10