0
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.

3
Contributors
2
Replies
3
Views
5 Years
Discussion Span
Last Post by berniefitz
0

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();
	}
}
0
BaseClass var = new SubClass();

Should be

SubClass var = new SubClass()

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

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.