c# - Why it is possible to assign partial methods to delegates in spite of other constraints? -
i know title might not totally clear, didn't want make long.
one thing boggles me when thinking restrictions placed on partial methods. seems me rules inconsistent. know:
partial methods must have return type of void, , cannot have parameters marked out modifier. these restrictions in place because @ run time, method may not exist , can’t initialize variable method might return because method might not exist. similarly, can’t have out parameter because method have initialize , method might not exist. [1]
it sounds sensible me. @ same time:
if there no implementing partial method declaration, cannot have code attempts create delegate refers partial method. again, reason method doesn’t exist @ run time. [1]
at first, these rules seem follow same compiler logic. there difference, though. stated in second quotation, compiler issues error when there no method implementation of partial method. why can't check implementation @ compile-time in other scenarios? allow more flexibility when using partial methods , logic behind rules identical.
i afraid answer can "because that's how implemented", maybe there more it?
[1] clr via c#, fourth edition
the whole point of partial methods facilitate extensibility in generated code scenarios without runtime performance impact. code generator emits partial method signature, , emits code calls partial method.
now, @ compile time, if method isn't implemented, these call sites entirely removed, , remaining code has valid. quotes confusing in regard, because they're talking "runtime existence" of method. that's nonsense: resolved @ compile time.
this reason difference: rules quoted first impose restrictions on method signature, whereas delegate rule imposes restriction on method usage.
the rules signature make sure can call method in manner code remain valid if method call removed. , intended use case partial methods them absent 99% of time. if require them implemented that's not feature should using in first place. use abstract method or alike.
building delegate method taking pointer method, , can't if method doesn't exist (well, suppose argue compiler replace delegate null
@ point, can't write, say, new action(null)
), yet there no reason disallow if method exist, implementer's convenience. code generator shouldn't emit code creates delegates method.
Comments
Post a Comment