Click here to Skip to main content
15,885,880 members
Please Sign up or sign in to vote.
5.00/5 (3 votes)
See more:
I have quick question regarding partial method implementation in partial classes of either vb.net or C#.

We know partial method implementation is optional however its declaration is mandatory.

Why do we need to declare a partial method if its implementation is not required. Why .NET compiler will not throw any compile error even we don't provide any implementation?

Are there any practical implementation to the above?

As always thanks for your time support.
Posted
Comments
Sergey Alexandrovich Kryukov 21-Feb-14 15:24pm    
Interesting question showing your critical thinking. I voted 5 for the question.
Be careful: I explained why one of the solutions is misleading. Please see my answer carefully; you can try it out to see what really happens.
—SA

You should clearly understand that partial methods are nothing but syntactic sugar, they don't affect any additional functionality, ever; they are designed only to improve code readability and make some steps on development process a bit more convenient. Only convenience, nothing about functionality. And absolutely none of those powerful feature Krunal tried to attribute in Solution 1.

Please see: http://en.wikipedia.org/wiki/Syntactic_sugar[^].

The possibility to have some non-implemented method is a somewhat delicate moment, so I'll have to illustrate it on some examples. In brief: this is not something to be taken too seriously. :-)

Let's start from the most extreme case of non-implemented method: let's declare it and even call, without implementation. The resulting behavior is something unusual. Let's see:
C#
public partial class PartialDemo {
    partial void Test(); //important: the method is private!
    internal PartialDemo() {
        Test(); // simply does nothing, can work during runtime
    } //PartialDemo
} //class PartialDemo

public partial class PartialDemo {
    // no implementation of void Test() yet
} //class PartialDemo
Pay special attention for my code comments, they explains pretty much everything.

This is what happens: the compiler statically detects that Test has no implementation. It compiles the code into IL in the following way: as if the method was never declared and called. Every piece of code behaves as if Test was never mentioned.

Now, the question is: why is is done so? For some, it would be convenient, but I personally don't need this feature much. This is done for one simple purpose: it is implied that the implementation will be written later, but without it, the code would still compile and even executed. I, for example, have a habit to re-compile code excessively often, because — why not? I write a line and re-compile. I write declaration without implementation — it compiles. So, for me, this is a bit of convenience, but I would easily leave without it. I would also suggest that adding this feature (not partial methods, but the ability to keep some methods not implemented) was decided under the influence of C/C++ culture, where there is a similar feature, albeit not really safe.

One thing you should understand: the code written above makes no sense. You never should write it without implementation for any thinkable functionality. You can consider this almost as a "compilable comment" saying: "implement it later". So, if you never add implementation later, it would defeat the purpose of using the feature in first place.

Now, all this feature (having no implementation) will work only of the partial non-implemented method is private. If it is public or protected (and the method is not abstract, of course), the compilation would make no sense at all. Public assumes that you can call the method from other assembly. But other assembly is compiled separately; it cannot "know" that in one case the the method exist and in other case it is not. This is a real call; and a call is a call. It won't compile even with internal. This design decision is not so critically important as with public or protected, but is reasonable. Let's see:
C#
public partial class PartialDemo {
    internal partial void First(); // WON'T COMPILE
    protected partial void Second(); // WON'T COMPILE
    public partial void Third(); // WON'T COMPILE
} //class PartialDemo

public partial class PartialDemo {
} //class PartialDemo
Each of those non-private methods will compile as soon as you add its implementation.

So, this feature cannot solve as any plug-in facility. Plug-ins can be based on reflection.

It also does not affect the possibility to auto-generate code. Remember, even before partial types were introduced, the auto-generated code was pretty much the same, only in one single file. That was very unreadable. Besides, it provoked used to update with the code the same file where the auto-generated code is. It could easily create a lot of mess. With partial types, it's a lot safer; in case of developer's mistakes, it's much easier to find ends. I personally often add my own partial declarations to types, in separate files, including auto-generated ones.

[EDIT]

However, Microsoft suggests and interesting way of using auto-generated code, the way fully based on the mechanism I described above. It is described in the MSDN article reference in Solution 3, second link. Credit to pwasswer for this link. Please see it.

Again, the idea is the same: isolation of the auto-generated code and the developer's code. In this approach, the auto-generated code uses unimplemented partial methods. In a separate file, in the other part of the same class, the user can add implementation to such methods. With recompilation, the non-existent calls to such methods are replaced with actual calls. This way, the user can inject the calls into auto-generated code by adding code in a separate part, and, hence, possibly in a separate file. You can think of it as of compile-time way of overriding which is not based on dynamic dispatch like in OOP, but is based on early binding. It does not have the OOP power, not at all, but it does not have that (tiny) overhead of the call of the virtual method. Hm…

It's important to understand that, from the stand point of functionality, this mechanism is 100% equivalent to just editing of the auto-generated code, adding some code to it and recompiling. But auto-generated code is not the real source code, in practice, it should not be edited. So, from the standpoint of project maintenance, it makes a big difference: isolation of auto-generated and developer's code.

So, I would speculate that this technique could be the major reason for .NET team to introduce partial methods without implementation. I am not sure I like it, because to me, it looks like adding an ad hoc feature for the sake of such a secondary goal as the techniques based on auto-generated code.

[END EDIT]


It just improves readability of code and ease up maintenance, if used reasonably. Pure syntactic sugar, no more.

—SA
 
Share this answer
 
v9
Comments
Ranjan.D 21-Feb-14 15:31pm    
+5
Sergey Alexandrovich Kryukov 21-Feb-14 15:46pm    
Thank you, Ranjan.
(By the way, you apparently forgot to actually vote. Thanks anyway... Since then, I improved the answer. :-)
—SA
[no name] 21-Feb-14 18:25pm    
+5. I'm happy you mentioned "syntactic sugar". Before a long long time (I'm pretty old;) ) I learned do not add e.g. methods to a class only because of convinience of use.
Kind regards, Bruno
Sergey Alexandrovich Kryukov 21-Feb-14 18:41pm    
Thank you, Bruno.
I tried hard, though you would like it... :-)

And I share this your principle of writing. This is one of the ideas which may not become obvious... Some dead code written as a placeholder for something to be implemented later contaminates code all the time before this "later" comes true and does not serve as a good reminder. Moreover, sometimes the initial idea becomes forgotten, and the you or even other people stare at the dead-code artifacts in disbelieve — "what the...". By those reasons, I enjoy partial classes, can use partial methods but not going to leave them not implemented for more than few minutes, because the clear alternative is not to create such methods at all before they are really needed. Moreover, almost the say may apply to non-called method. Each method just created should mentioned in the calling code pretty soon or its implementation should be deferred. But this call could be done just from the testing unit, which is another, well known idea — test-driven development (hopefully not pedantically reduced to absurd — development method for development methods; with time, I realized that most of development-method literature is the typical pure pseudo-science).

"Ideas for future" can be documented somewhere separately. Having a good issue tracking tool is one of the good ideas...

At the same time, those are all the ideas for personal development practices and hence are pretty delicate and should be applied depending on individual human features and taste. It is utterly silly to make big and rigid policies out of them, as some try to do.

—SA
Sergey Alexandrovich Kryukov 22-Feb-14 0:19am    
By the way, please pay attention for new section in [EDIT]... [END EDIT].
—SA
I read with interest the discussion so far. It leads me to these points:

1. The msdn is not the best way to understand why partial methods exist.
2. Quoting verbatim from elsewhere has its dangers.

The top answer here gives some leads and refers to LINQ:
http://stackoverflow.com/questions/42187/how-are-partial-methods-used-in-c-sharp-3-0[^]

This explains that point further:
http://msdn.microsoft.com/en-us/library/bb546176(v=vs.110).aspx[^]

Finally this:
http://stackoverflow.com/questions/3628804/why-you-need-partial-methods-in-c-can-events-be-used-to-achieve-the-same-goal[^]
 
Share this answer
 
v2
Comments
Sergey Alexandrovich Kryukov 21-Feb-14 19:50pm    
Where is the discussion you refer to? It's almost all my talking. Solution 1 is probably based on the referenced posts, also misleading and not argumented. We did not do the dialog, almost.

Anyway, I really appreciate your thinking in items 1-2.

Second one is not just absolute truth, it is 500% of truth. I mean, it's not just truth, it's the truth to be nailed in the head of many developers (especially some of our "experts") with a big hummer.

#1 is not really accurate though. I just think that this is not what you meant to say yourself. Probably you meant to say "MSDN cannot be always trusted". That would be true. Not the best? How would you know? Do you know any better source? I don't know, and I cannot know that because I cannot read everything. So far, I saw a lot of total trash in some books and only few poorly documented MSDN articles. Some are utterly bad, but not too many of them.
If you prove me wrong (by pointing out better source than MSDN), I will be very grateful.

Now, is there the way to ascertain the truth? In many case, there is. You can create an exhaustive set of probe code. No, I am not talking about testing. We should understand: testing does not prove anything. No, I mean this: you can use the debugger, reflection and you can disassemble the code. This is what I do in difficult situation to check up some claims on how some mechanisms work. There are such difficult cases, where the documentation can be incomplete or even just misleading.

Unfortunately, you did not tell us your opinion on the answers you referenced. You also did not comment on my answer. I didn't take time to analyze them all, but I can see that at least some of them are based on misunderstanding or incomplete understanding.

And I am grateful for your reference to MSDN article "Adding Business Logic By Using Partial Methods". There is nothing wrong or misleading in it. It just explains a real idea which I did not think of, on code generation and using those unimplemented partial methods. It really works (actually, it becomes apparent based on the mechanism I described in my answer). This can be considered as the overriding mechanism based on early binding. I just don't think this is a good idea.

So, after some thinking, I voted 4 for the answer, as it helps to understand thing and provides some food for thought. The problem is that you don't clearly express your opinion on the subject...

—SA
Sergey Alexandrovich Kryukov 21-Feb-14 23:41pm    
...and after some more thinking, I added as section to my answer (please see between [EDIT]... [END EDIT]) and credited your answer for this link.

Thank you very much!

I also realized what was wrong with my "I just don't think this is a good idea". I actually explained what I really don't like about it, in my [EDIT] section. I should rather have said "there is still nothing special about it", from the functionality and runtime standpoint, but the idea itself is pretty interesting. After all, I do use auto-generated code myself, I only suggest not to overuse such things and not take it too seriously, use applying critical thinking.

—SA
A partial method is like a usual method in a class except that the user may or may not implement it. A partial method gets executed only when it has an implementation. What is the use of a method that does not have an implementation? Such methods can act as hooks for plugging in code, for instance take a code generation tool that generates a class. It can have partial methods, the user of the class can implement them or just leave them. If the user leaves them, the compiler does not include them in the final code thus improving the overall performance. If the user writes some implementation code for them, then they act as normal methods.

The use of partial methods improves the performance because any call to a partial method without an implantation is removed from the assembly code by the compiler. Partial methods are intended to solve a major problem that is caused by code-generation tools. Similar functionality can be achieved with sub classing, but it creates a performance overhead and moreover partial methods are more clear to understand.
See the whole article here[^].

Partial methods are particularly helpful for customizing auto generated code by the tool. Whenever the tool generate the code then tool may decalare some partial method and implementation of these methods is decided by the developers.

For Example, go here[^], here[^] and here[^]
And yet MSDN[^] is there. :)

-KR
 
Share this answer
 
Comments
BillWoodruff 21-Feb-14 10:44am    
+5 very well-written and useful
Krunal Rohit 21-Feb-14 10:45am    
Thanks Bill :)
-KR
Sergey Alexandrovich Kryukov 21-Feb-14 11:28am    
Bill, unfortunately, I have a serious, really serious doubt about it.
Please see my comment below.
—SA
Sergey Alexandrovich Kryukov 21-Feb-14 15:23pm    
I added my own answer, a correct one.
This answer is completely misleading, based on misunderstanding.
—SA
Sergey Alexandrovich Kryukov 21-Feb-14 11:27am    
I cannot see how the partial methods can act as hooks for plugging in code. Not at all. If you can explain it with examples, it would be great, otherwise it would be just a claim and a misleading statement. This is a very important point. If it was possible, partial methods would be a powerful instrument.

I think they are not, just a syntactic sugar. They are totally irrelevant to behavior of the system. Only help to create near code. Even auto-generated code. As well as with partial classes: they help to isolate auto-generated part of the class from user-written part. But it does not affect behavior of the already compiled code, ever. Am I wrong? I don't think so.

Now, your considerations about performance are simply wrong. You don't take into account that all the code is JIT-compiled. Even when a method is implemented but never called, normally, it will never be compiled. This is how JIT-compilation works. Did you know that? Probably not. I am sure that your considerations are just speculations; you never actually measured the change in performance. Otherwise you would find out that such difference in performance does not exist. And, to measure it, you would need to exclude JIT compilation phase. This can be done.

If you can prove I'm wrong, I will be very impressed. So far, I think that the whole answer, really well written, is misleading.

—SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900