Search This Blog

2012/03/13

Access Modifier of Derived Class Member

 Access Modifier in csharp is one of the most neglected topic,we many times try to to modify our code to remove the errors yet we seldom look into it as topic of interest,here in this article I explore access modifier in reference to  virtual function and inheritance

Consider Code Sample Below of a simple console application.

namespace AccessiblityAndMemberClass
{
class Program
{
static void Main(string[] args)
{
}
}

class MyBaseClass
{
protected virtual string GetClassName()
{
return "MyBaseClass";
}
}
class MyDerivedClass : MyBaseClass
{
public override string GetClassName()
{
return "MyDerivedClass";
}
}

}

Here MyBaseClass is Base class having protected virtual method "GetClassName",now when "MyDerivedClass" class which inherit from "MyBaseClass" try to override this method by widening access modifier code doesn't compile

This Scenario explains in derived class can't widen restrictive access modifier if specified in Base class.

Now consider one more code sample

class MyBaseClass1
{
public virtual string GetClassName()
{
return "MyBaseClass";
}
}
class MyDerivedClass1 : MyBaseClass1
{
override string GetClassName()
{
return "MyDerivedClass";
}
}

Here I tried to restrict access modifiers in derived class for method GetClassName that one is also not allowed.

Moral of the story is in csharp keep access modifier of derived class member same as base class if member is virtual method/function.

No comments:

Post a Comment