c# - Is it possible to limit extension methods in a class to be of specific type? -
this requirement driven grief peer developers mix extension method on different types 1 xxxext class. still works because compiler takes care of resolution looking @ imported namespaces. annoying , not easy maintain when comes overlapping types.
is @ possible constraint type extensions written in specific xxext class? circulating manual rules not work well... possibly static code analysis if not compiler level restriction?
code (which want restrict in class isactiverisk method).
public static class tradedataext{ public static bool isactivetrade(this tradedata tradedata){...} public static bool isactiverisk(this riskdata riskdata) {...} }
this more of "desired" feature, not sure if @ possible. comments/suggestions helpful.
first of all, seems me wrote example , forgot more important keyword of extension methods, missed keyword "this" right before parameter! :)
i'm guessing meant:
public static class tradedataext { public static bool isactivetrade(this tradedata tradedata){...} public static bool isactiverisk(this riskdata riskdata) {...} }
ok, first point said, let's take @ question:
this requirement driven grief peer developers mix extension method on different types into 1 xxxext class.it still works because compiler takes care of resolution by looking @ imported namespaces.
in fact, saying exact opposite of truth of how extensions methods work!
when declare static class static methods, methods automatically available when declaring using "namespace", , not of name of class! (unless in scenario have project several .cs files partial classes of same static class..... think not make sense)
take @ example:
namespace gabriel.extensions { public static class classwithsamename { public static bool isactivetrade(this tradedata tradedata){...} } } namespace john.extensions { public static class classwithsamename { public static bool isagooddeal(this tradedata tradedata){...} } }
if @ example, both classes have same name, since in different namespaces, extend tradedata class when explicitly declaring "using" of each namespace. so, way go you:
you should use namespaces control types extensions being created, can have namespace xxxx.extensions.validation, xxxxx.extensions.calculation, xxxxx.extensions.servicesprovider , on... instead of using @ same namespace (because things can complicated...add hundreds of extensions methods in same namespace, not best practice @ all.
your code should this:
namespace tradedataextensions.validation { public static class classwithsamename { public static bool isactivetrade(this tradedata tradedata){...} } } namespace tradedataextensions.analytics { public static class classwithsamename { public static decimal expectedreturn(this tradedata tradedata){...} } }
Comments
Post a Comment