c# - Using a generic type argument in place of an argument of type System.Type. Is it a smell? -


i see (in many mocking libraries example) methods generic type argument used in place of argument of type system.type. talking cases generic type being used in typeof(t) operation (i.e. no instance of type t being used anywhere within method, , t not being used either return type or other arguments).

for example consider following method:

public string gettypename(system.type type) { return type.fullname; } 

this method accompanied generic version:

public string gettypename<t>() { return gettypename(typeof(t)); } 

questions bad practice or practice?
syntactic sugar or there more it?

i see misusing language feature abbreviate call method accepts argument of type system.type

would consider smell? should avoided? or practice (to provide generic method shortcut avoid typing typeof()).

here practical issues using pattern can think of:

  1. if argument of non system.type type added - method might need rewritten (if order of arguments semantically significant) non generic version (otherwise arguments generic type arguments, , regular arguments).
  2. it requires 2 methods (generic , non generic cases type not known @ compile time). consequently adds unit tests meaningless.

on other hand common practice (and majority right, right?) more importantly resharper prefers signature when extract method refactoring on code requires single argument of type system.type known @ compile time (and learned take recommendations though not on faith, seriously).

i think need consider documentation. how obvious methods do? if have 2 methods (one type , 1 type argument), users need @ both , choose. people aren't looking @ code may not realize second 1 calls first.

where makes sense use both when type argument used when can , there kind of fallback type version. example:

object getthingoftype(type type) { ... }  t getthingoftype<t>() { return (t)getthingoftype(typeof(t)); } 

another thing consider: type argument must written explicitly. if there more 1 operation perform same type object, it's not helpful use type arguments. consider this:

var t = typeof(string); var name = gettypename(t); var assemblyname = t.assembly.fullname; 

even though know type string, should not write gettypename<string> here because repeating myself. giving me option better off not choosing, you're adding bit of unnecessary complexity.

a more obscure point ide support of xml documentation. document type argument this:

<typeparam name="t">important information</typeparam> 

then if type gettypename< in c#, visual studio show "t: important information". but, reason, when type gettypename(of in visual basic, not (as of 2012).


Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -