Jacques R
Jacques R

Reputation: 387

Can I use a derived class function if base class is called as parameter?

I have a class with public MyClass(Form form) as constructor

Is it possible for me to use the functions I made in a class derived from Form in this class? (Named DerivedClass)

For now I was thinking, check if form is DerivedClass then use its functions, but it doesn't seem to work.

if (form is DerivedClass)
{
    form.DerivedClassFunction();
}

Doing this I get the same error :

"Form" does not contain a definition of "DerivedClassFunction"

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-messages/cs1061?f1url=%3FappId%3Droslyn%26k%3Dk(CS1061)

Upvotes: 1

Views: 432

Answers (1)

SomeBody
SomeBody

Reputation: 8743

You have to convert it to your derived type, either via:

if (form is Derived)
{
    ((Derived)form).DerivedClassFunction();
}

or (new in C# 7):

if (form is Derived derived)
{
    derived.DerivedClassFunction();
}

Upvotes: 6

Related Questions