c# - Return specific type in generic method -


i have written following method:

public t createpackage<t>() t : new() {         var package = new t();          if (typeof(componentinformationpackage) == typeof(t))         {             var compinfopackage = package componentinformationpackage;              // ...              return compinfopackage;         }          throw new system.notimplementedexception(); } 

i check type t , according treat variable package. when want return compiler error.

"the type componentinformationpackage cannot implicitly converted t"

how can solve problem?

first: cast doesn't work, safe cast does work:

return compinfopackage t; 

...provided there's class constraint on t:

public static t createpackage<t>() t : class, new() { ... } 

second: given code:

var package = new t(); if (typeof(componentinformationpackage) == typeof(t)) {     var compinfopackage = package componentinformationpackage;      // ...      return (t)compinfopackage;  } 

...you have reference package new object. since it's of type t, compiler likes return type. why not return that?

var package = new t(); if (typeof(componentinformationpackage) == typeof(t)) {     var compinfopackage = package componentinformationpackage;      // ...      return package; // same object compinfopackage } 

it works structs.


Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

javascript - Get parameter of GET request -

javascript - Twitter Bootstrap - how to add some more margin between tooltip popup and element -