sealed method question.

A

avnrao

Hi,

I am curious about how to write C# class with this requirement : I want to
make one of the methods of the class to be non overridable in derived
classes.
I cannot use sealed because sealed keyword on a method should also have
override keyword. My class here is the master class.

Consider a class Master with 2 methods

public class Master
{
public virtual string Method1()
{
}
public string Method2()
{
}
}

public class Child : Master
{
public override string Method1()
{
}
}

how to make Method2 as non-overridable and Method1 as overridable by Child
class?
 
D

Dennis Myrén

Methods can not be overridden unless they are virtual or abstract or
overridden
from a lower class.
 
J

Joey Callisay

your code is good.

Method1 is non-overridable (since it is not virtual). The only way for its
child classes to define their own Method1 is if it gets shadowed or newed.

public new string Method1()
 
R

Richard Blewett [DevelopMentor]

As Dennis say, you don't have to anything special to make a method non-overridable as that is the default in C# (unlike Java). This means that a base class developer has to think explicitly about how they want derived classes to interact with their code and make the methods that want to be replacable virtual (or abstract).

Regards

Richard Blewett - DevelopMentor
http://staff.develop.com/richardb/weblog

Methods can not be overridden unless they are virtual or abstract or
overridden
from a lower class.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top