using System;
using System.Collections.Generic;
using System.Text;

class BaseClass
{
    public virtual void method() 
    { Console.WriteLine("BaseClass method"); }
}

class SubClass : BaseClass
{
    public override void method() 
    { Console.WriteLine("SubClass method"); }
    
    public void someMethod() 
    { Console.WriteLine(); }
    
    static void Main(string[] args)
    {
        BaseClass var = new SubClass();
        
        var.method();
        var.someMethod();
    }
}

The above code does not compile for var.someMethod() statement because var's type is BaseClass. Although var is an object of SubClass which contains the someMethod(). Could someone help. Thanks in advance.

Recommended Answers

All 2 Replies

I haven't really touched C# before but I'm pretty sure (since in C++ you have to) you need to have BaseClass as an abstract class and then declare someMethod() as abstract within it. This is because you are trying to call a function in SubClass when BaseClass has no idea what functions you have added to SubClass (it only knows the functions/variables that it gives to SubClass).

using System;
using System.Collections.Generic;
using System.Text;

abstract class BaseClass
{
	public virtual void method()
	{ Console.WriteLine("BaseClass method"); }
	public abstract void someMethod();
}

class SubClass : BaseClass
{
	public override void method()
	{ Console.WriteLine("SubClass method"); }

	public override void someMethod()
	{ Console.WriteLine("abstract method"); }

	static void Main(string[] args)
	{
		BaseClass var = new SubClass();

		var.method();
		var.someMethod();
	}
}
BaseClass var = new SubClass();

Should be

SubClass var = new SubClass()

Your var is still a SubClass which is a sub-class of BaseClass

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.