c# - Is there any benefit (semantic or other) to using a static method that calls a constructor? -
i updated visual studio 2013 , noticed in project template mvc application applicationdbcontext class has static method calls constructor:
public static applicationdbcontext create() { homecoming new applicationdbcontext(); }
this seems clutter me imagine there semantic reason should start using applicationdbcontext.create()
instead of new applicationdbcontext()
. there benefits doing so?
actually. yes.
in specific case, wrapping thusly allows start bolting on logic, such making applicationdbcontext , singleton or handling exception in mutual way whole application. since constructor cannot homecoming null, can of import able grab exception , homecoming null.
tuple.create prime illustration of generic inference, not work constructors. allows say
tuple.create(item1, item2.. itemn);
and allow compiler infer types, rather than
new tuple<t1, t2...tn>(item1, item2...itemn);
which more verbose, , takes bit more work if want switch out 1 of types.
there case of anonymous types, cannot specified explicitly , cannot used in new statements. have had occasion where, while searching assemblies specific attribute link command construction for, wanted create enumerable (a queue, in case) out of anonymous type during search pair class references constructor , string arguments, rather looking these every time they're needed. since can 1 time again utilize generic inference in method, able wrap constructor in extension method , job done.
there cases singleton patterns, wherein want "getinstance" method create value, or 1 if exists. may not qualify since more wrap constructor.
in addition, there plenty of cases may want command implementation procedures, such forcing them onto other threads, logging them in database undone later, or bolting on permissions system, of can done making constructor wrapper , adding few more lines of logic, , privatizing constructor avoid beingness called directly.
there cases i've created mill method delegates known children in order provide different implementation of returned interface or abstract based on provided parameters. has added benefit of beingness able hide implementing classes - type class , ienumerable interface create utilize of pattern.
c# constructor static-methods
No comments:
Post a Comment