Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do partial methods have to be void?

Tags:

c#

I am currently learning C# with the book called Beginning Visual C# 2010 and I am in the chapter that discusses different aspects and characteristics of partial methods and classes.

To quote the book:

Consider at this point why partial methods can’t have a return type. If you can answer that to your own satisfaction, you can be sure that you fully understand this topic — so that is left as an exercise for you."

This is where I get stuck. The only reason that I can think of is that when the method's return value is assigned to something in the code, it would generate an error if there is no definition implemented for the partial method.

Can someone clear this topic for me please?

like image 580
Gasoline Avatar asked Aug 05 '11 09:08

Gasoline


People also ask

What will happen if there is an implementation of partial method without defining partial?

Similar to a partial class, a partial method can be used as a definition in one part while another part can be the implementation. If there is no implementation of the partial method then the method and its calls are removed at compile time. Compiler compiles all parts of a partial method to a single method.

What is the use of partial methods?

A partial method has its signature defined in one part of a partial type, and its implementation defined in another part of the type. Partial methods enable class designers to provide method hooks, similar to event handlers, that developers may decide to implement or not.

Why do we need partial methods in C#?

Partial methods enable the implementer of one part of a class to define a method, similar to an event. The implementer of the other part of the class can decide whether to implement the method or not. If the method is not implemented, then the compiler removes the method signature and all calls to the method.

Do partial classes have to be in same namespace?

All parts of a partial class should be in the same namespace. Each part of a partial class should be in the same assembly or DLL, in other words you can't create a partial class in source files of a different class library project. Each part of a partial class has the same accessibility.


1 Answers

Because calls to them can't be eliminated from the calling code in case they are not implemented without breaking it.

Example:

partial void foo();
partial int bar();

Calling code:

...
foo(); // successfully removed if foo isn't implemented
int x = bar() * 2; // what to do here?
Console.WriteLine(x);
like image 123
Grozz Avatar answered Sep 30 '22 19:09

Grozz