why i need partial class and virtual method in c#? - c#

i have a question, why there is a partial class and a virtual method in c#?
i mean what is the difference when i have a normal or abstract class and then inherit from it or make it partial?
the other question is why i need virtual methods? when i inherit from a class i also can override the method if i want.

Partial classes: they're mostly there to allow machine-generated code to be combined with manually-generated code at compile time, to avoid abusing inheritance etc. It can be used for other reasons, but that's the main purpose of them. No more source files with "don't edit this bit - it belongs to the designer" etc.
Virtual methods: no, you can't override a member if it's not declared virtual (or abstract) in the base class. You can shadow it with new, but that's not the same as overriding it - the new method won't be called polymorphically.

Partial classes and methods allow you to spread code across different files. This is useful when you use code generation - the generated code is in one file that can get overwritten without a problem, the rest of the code can be changed safely.
As for virtual - in C#, if you want to override a method, you must use virtual (or abstract) in the base class and override in the overriding class. You can't simply override without them.
If you don't use virtual/abstract and override you are in danger of hiding/shadowing a method, which may or may not be what you want. Using virtual/abstract and override make things explicit and predictable.

Partial classes lets you split a class definition across multiple files, which is practical in some scenarios.
No; you can only override a method if it is marked as virtual in the base class. If the base class' method is not virtual and you create a method with the same name in the subclass, you have created an entirely new, unrelated method.

Partial classes allow you to split up a class definition across several files.
A virtual method may be overridden using the keyword override. If the method is not defined as virtual you can only hide it in a child class using the new keyword.
I guess you can read all this up in any C# 101 material. Just take a look at the MSDN library.

A partial class let's you define the same class in multiple declaration which are mostly in different files also. Like:
public partial class MyClass{
public void MethodOne(){}
}
public partial class MyClass{
public void MethodTwo(){}
}
A virtual method can be used if a subclass of the baseclass has the ability to override the method. Use abstract if your subclass MUST override the method. So,
public class MyBaseClass{
public virtual void MethodOne(){} // CAN be overridden...
public abstract void MethodTwo(){} // MUST be overridden.
}

Partial classes are useful to divide a single class in multiple files in the same project.
This is very useful for tools that generates code for you, like windows form or WPF.
Partial classes allow you, for example, to write your code in one file and let the IDE write his code in another file.
About virtual and override, look at this other thread: Why do we use virtual and override?

Related

Limit scope of method for child implementations

I hope this isn't a duplicate but I can't find one via Google or SO search. If I want to force the accessibility for a method's implementation of an overridden method to be protected, is my only option to either create as abstract or protected virtual? I know that interfaces specify the declaration but leave the accessibility/scope to the class implementation but I'd like to be sure.
I'd like to know/be certain of if the only way to limit the scope of a method is via a abstract \ protected virtual to give semantics of "this applies to the class implementation or the child override implementation".
A code sample to illustrate. I know I can do the following and limit the scope of an implementation like so;
public class BaseClass
{
protected virtual void OnlyMeOrChildrenCanDoAction()
{
// leave empty as current class is structural/conceptual
// but child instances may need it
}
}
By doing the above I guarantee that child implementations can only override OnlyMeorChildrenCanDoAction()as protected but not public.
But is there another way of limiting to protected without resorting to abstract or protected virtual? An example of creating a method like this is Object.Finalize() as seen here.
Or, to invert the question somewhat, why would you create a method as protected virtual unless to ensure that any implementations were limited in scope? Or is there another way to do the same?
I think you're misunderstanding the meaning and use of virtual. You can only override a method in the parent class if it is declared virtual. The override method in the child class must have the same visibility as the method in the parent class.
Implementations of methods declared in interfaces are always public.
Declaring a method abstract has the same effect as declaring it virtual, except you do not implement it in your class and any concrete classes that derive from your class must implement it.
Technically, the compiler will not allow you to change the access modifiers of a method when overriding it from the parent, so the answer to the question is that by declaring a method as protected within a class, you are only making it available to derived classes (whether abstract or not is a separate concern and doesn't bear on the access level).
Keep in mind, however, that derived class would be free to expose the function in some other way such as calling the protected method from a public one and there is no way to prevent that.
As far as "why" you would have a protected abstract member, a great example can be seen in many implementations of the Template Method pattern. You may have an abstract base class that describes the structure of an algorithm and leave the specific steps of what happens inside the boundary of each step to derived classes. In this case, one way to implement would be to declare the base class as abstract, have a public method serve as the "entry point" for the algorithm, and define specific methods used within the algorithm as protected abstract methods to lay out what the responsibility of derived classes will be. This pattern does a nice job of leaving public only those things that are intended to be consumed by the world, but can present some challenges from a unit testing perspective which are sometimes addressed by raising the visibility of the helper methods from protected to internal.
You cannot use the c# language to prevent a derived class from implementing a public version of OnlyMeOrChildrenCanDoAction. Even if you mark it as protected virtual, the derived class can use the new keyword to cover the method and change its accessibility. For example:
public class BaseClass
{
protected virtual void OnlyMeOrChildrenCanDoAction()
{
// leave empty as current class is structural/conceptual
// but child instances may need it
}
}
public class DerivedClass : BaseClass
{
public new void OnlyMeOrChildrenCanDoAction()
{
Console.WriteLine("This is public.");
}
}
public class Program
{
public static void Main()
{
var b = new BaseClass();
//b.OnlyMeOrChildrenCanDoAction(); //Will not compile
var d = new DerivedClass();
d.OnlyMeOrChildrenCanDoAction(); //Look! It's public!
}
}
Output:
This is public.
Code available on DotNetFiddle.
If you want to protect the caller from calling OnlyMeOrChildrenCanDoAction, your best bet is for the caller to use only interfaces. If OnlyMeOrChildrenCanDoAction isn't in the interface, there is no way a caller could call it, even if a derived class decided to expose it as a public class member. This is good SOLID design anyway.
On the other hand, if you're not so much worried about the caller as you are worried about your own development team doing bad things, perhaps your best option is to use FxCop or some other source code rules engine integrated into your continuous build process. Developers could still add the method but you could set up a rule to cause it to fail the build if they do so.

C# - when do I need override? When don't I need it?

I am using C# with Unity3d.
When I use Monobehaviour and create an Update method, I don't need to use the override keyword.
When I create my own class and override a function, I do need to use the override keyword.
Why is that? Why do I not need the override keyword when creating the Update method?
I think your confusion comes from the fact that Unity does something special about these methods (Update, Start, Awake, etc). You can declare them as private and even then they will be called. That's not achievable using the language unless you use reflection, but I was told they don't use it, so I don't know what they do. And honestly, it doesn't matter. Because you can think as this being an exception to the language, that is, these methods will be called if you implement them. Simply that.
For all the rest, you have to follow the language. Here is a rough explanation:
You can or have to override a method if it is marked as abstract or virtual in the base class.
A method is abstract when the base class wants its children to implement it. A method is virtual when the base class offers an implementation of it but also offers an opportunity for the children to implement/modify that method.
So why can't all methods be "overridable"? To protect the base class developer's intention. You'd be changing the behaviour of a base class, you don't know if the base class developer would like you to do this. It's like a security lock. So that's why you have the three words abstract, virtual and override, to communicate the API intentions from the base class to their children.
You need to use the override, when you derive a class from another class and you need to change the code of a method of the base class that is virtual. This way the inheritted method of the base class can have a different behaviour -more suitable- for the derived class.
More generally, as it is stated in MSDN:
The override modifier is required to extend or modify the abstract or virtual implementation of an inherited method, property, indexer, or event.

How to "properly" override a base class method?

Whenever i override a method of a base class, other than my implementation of this method, i seem to have 3 choices.
1) Call base.Method(), and then provide my implementation.
2) Provide my implementation and then call base.Method()
3) Just provide my implementation.
Recently while using a library i have realized few bugs that were introduced because of not implementing the method as expected by the library. I am not sure if that is bad on part of library, or something wrong in my understanding.
I will take one example.
public class ViewManager {
public virtual void Customize(){
PrepareBaseView();
}
}
public class PostViewManager {
public override void Customize(){
base.Customize();
PreparePostView();
}
}
public class PreViewManager {
public override void Customize(){
PreparePreView();
base.Customize();
}
}
public class CustomViewManager {
public override void Customize(){
PrepareCustomView();
}
}
My question here is that how could a child class know (without taking a look at base class implementation) which order (or option) is being expected by the parent class?
Is there a way in which parent class could enforce one of the three alternates to all the deriving classes?
how could a child class know (without taking a look at base class implementation) which order (or option) is being expected by the parent class?
There is no way to "know" this when you are subclassing and overriding a method. Proper documentation is really the only option here.
Is there a way in which parent class could enforce one of the three alternates to all the deriving classes?
The only option here is to avoid the issue. Instead of allowing the subclass to override the method, it can be declared non-virtual, and call a virtual method in the appropriate place. For example, if you want to enforce that subclasses "call your version first", you could do:
public class BaseClass {
public void Method() // Non-virtual
{
// Do required work
// Call virtual method now...
this.OnMethod();
}
protected virtual void OnMethod()
{ // Do nothing
}
}
The subclasses can then "override" OnMethod, and provide functionality that happens after "method"'s work.
The reason this is required is that virtual methods are designed to allow a subclass to completely replace the implementation of the parent class. This is done on purpose. If you want to prevent this, it's better to make the method non-virtual.
This is why I feel virtual methods are dangerous when you ship them in a library. The truth is you never really know without looking at the base class, sometimes you have to fire up reflektor, read documentation or approach it with trial and error.
When writing code myself I've always tired to follow the rule that says:
Derived classes that override the protected virtual method are not required to call the base class implementation. The base class must continue to work correctly even if its implementation is not called.
This is taken from http://msdn.microsoft.com/en-us/library/ms229011.aspx, however this is for Event design though I believe I read this in the Framework Design Guidelines book (http://www.amazon.com/Framework-Design-Guidelines-Conventions-Libraries/dp/0321246756).
However, this is obviously not true, ASP.NET web forms for example require a base call on Page_Load.
So, long and short, it varies and unfortunately there is no instant way of knowing. If I'm in doubt I will omit the call initially.
The short answer is no. You can't enforce in what order the child calls the base method, or if it calls it at all.
Technically this information should be included in the base object's documentation. If you absolutely must have some code run before or after the child class' code than you can do the following:
1) Create a non-virtual function in the base class. Let's call it MyFunction
2) Create a protected virtual function in the base class. Let's call it _MyFunction
3) Have deriving classes extend the _MyFunction method.
4) Have MyFunction call _MyFunction and run the code it needs to run before or after calling it.
This method is ugly and would require a lot of extra code, so I recommend just putting a notice in the documentation.
The requirements of the base class should be documented by the library designer.
This issue is the reason why some libraries contain mainly sealed classes.

internal abstract methods. Why would anyone have them?

I was doing some code review today and came across an old code written by some developer. It goes something like this
public abstract class BaseControl
{
internal abstract void DoSomething();
}
If you have a derived class within the same assembly, it would work
public class DerivedControl : BaseControl
{
internal override void DoSomething()
{
}
}
But deriving the base class in a different assembly would give compile time error
DerivedControl does not implement inherited abstract member 'BaseControl.DoSomething()
That got me thinking. Why would anyone declare a method as internal abstract ?
The original programmer wanted to make a derived control available to client code. But prevent the client from inheriting and messing with the virtual method. That's not a bad idea, it is usually easy to break a base class by overriding a method and doing something like forgetting to call the base class method.
One obvious case is where the method receives or returns an internal type. For example, the core methods of the WPF Transform classes process some internal interop types, which WPF doesn't expose as part of its public API. Because the signature includes internal types, the method can't be public or protected. And yet clearly it's appropriate (necessary!) for the various Transform classes to work polymorphically. Therefore the base methods in Transform/GeneralTransform have to be internal.
Another, but related reason is to prevent external derivation. After all, the WPF architects could have exposed a "safe" version of the internal interop types in a protected abstract method, so that users could create their own Transform classes. They didn't because they didn't want to have to cope with the ways that people might use that capability, e.g. creating non-affine transforms. Allowing external derivation would have made the job of other classes in WPF hugely more complex, so the architects decided to allow only "approved" derived classes by making an abstract method internal.
My initial reaction was that there is no good reason, if you want to prevent external inheritance then you should mark the class internal. But that means that the class is totally hidden to other assemblies.
I suppose this method prevents external inheritance while retaining visibility.
By defining a method as internal abstract you want to make sure that only the class in the same assembly can have its implementation for your method.
now if you distribute a dll of it this will avoid the client to inherit and mesup the implementation.

Partial classes/partial methods vs base/inherited classes

a question about class design. Currently I have the following structure:
abstract Base Repository Class
Default Repository implementation class (implements some abstract methods, where logic is common thru all of the Specific classes but leaves other empty)
Specific Repository implementation Class (implements what is left empty in the above Default class)
I've now came to the problem where I have a specific Update() method in Specific class but when all the code in this method executes some code from the base Default class should be executed too.
I could do it like this
public override Update()
{
// do Specific class actions and updates
// ....
// follow with base.Update()
base.Update();
}
but this requires those base.XYZ() calls in all the inherited methods. Could I go around that somehow with partials?
So the requirement is to have code in both parent and inherited class (or to make those two one class using partials) and code from method implementation in both places should be executed. Also what about if I wanted to turn it around and execute base class code first followed by the inherited class code?
thanks
Have you considered something like:
public abstract class YourBaseClass
{
public void Update()
{
// Do some stuff
//
// Invoke inherited class's method
UpdateCore();
}
protected abstract void UpdateCore();
}
public class YourChildClass : YourBaseClass
{
protected override void UpdateCore()
{
//Do the important stuff
}
}
//Somewhere else in code:
var ycc = new YourChildClass();
ycc.Update();
All the partial keyword means is that the definition of the class is split between source files:
It is possible to split the definition of a class or a struct, an interface or a method over two or more source files. Each source file contains a section of the type or method definition, and all parts are combined when the application is compiled.
There still has to be a complete definition of the class in the project.
You'd be better off creating a subclass, that way you can override specific methods.
As far as partial methods go (from the same link as above):
A partial method declaration consists of two parts: the definition, and the implementation. These may be in separate parts of a partial class, or in the same part. If there is no implementation declaration, then the compiler optimizes away both the defining declaration and all calls to the method.
// Definition in file1.cs
partial void onNameChanged();
// Implementation in file2.cs
partial void onNameChanged()
{
// method body
}
You can't have half the method in one file and the other half in another.
Here's how you can do this:
public sealed override void Update()
{
UpdateCore();
base.Update();
}
public abstract /* or virtual */ void UpdateCore()
{
// Class-specific stuff
}
Forget about partial, that has entirely different semantics. Whether the overrider of your virtual base class method should call the base class method is not automatic. It needs to be part of your documentation. A good example are the OnXxxx() methods in the Control class, the MSDN library docs have a "Note to implementer" comment that warns that calling the base class method is usually necessary.
If you make the base class method abstract then it is crystal-clear to the overrider. If it is not, you are dropping a strong hint that it ought to be done. If you expect the override to completely replace your base implementation then you should really consider making it abstract. This ambiguity, combined with the odds that the overrider breaks your base class by overriding incorrectly, is definitely one of the weak points of polymorphism.
Add a new virtual (not abstract, since not all specific implementation need to override it?) method to your Default implementation to accommodate inheritors having their own additional steps on top of it's own implementation.
Call the virtual method at the appropriate point in the Default Implementation's abstract method implementation.
You've left your abstract class as it is and transparently grown the flexibility of the default implementation.

Categories