Unknown Generic Type cannot be NULL and default(T)

Lets say we are creating a generic method of type T used to convert one type into another. That being said there might be a type conversion exception thrown within the method, if this happens we want to simply return a null indicating that the conversion did not happen correctly. Unfortunately, generic types cannot be set to null, this is because a generic type could be a reference type or a value type depending on what is passed in. Because of this possibility and the fact that value types cannot be implicitly converted to null you must use a new ‘default’ keyword which checks the passed in type to see if it evaluates to a reference type or a value type, if a reference type the passed in type is set to null, if a value type it is set to the default value for that value type.

8 internal static T Cast(object o)

9 {

10 T value;

11

12 try

13 {

14 value = (T) o;

15 }

16 catch

17 {

18 value = default(T);

19 }

20

21 return value;

22 }

Published by

Tim Clark

Experienced Business Owner, Chief Information Officer, Vice President, Chief Software Architect, Application Architect, Project Manager, Software Developer, Senior Web Developer, Graphic Designer & 3D Modeler, University Instructor, University Program Chair, Academic Director. Specialties: Ruby, Ruby on Rails, JavaScript, JQuery, AJAX, Node.js, React.js, Angular.js, MySQL, PostgreSQL, MongoDB, SQL Server, Responsive Design, HTML5, XHTML, CSS3, C#, ASP.net, Project Management, System Design/Architecture, Web Design, Web Development, Adobe CS6 (Photoshop, Illustrator)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s