Author Topic: TNSerializer structs  (Read 2073 times)

Simie

  • Newbie
  • *
  • Thank You
  • -Given: 0
  • -Receive: 0
  • Posts: 25
    • View Profile
TNSerializer structs
« on: June 18, 2014, 11:33:15 AM »
In the method TNSerializer.Create(this Type type) (TNSerializer.cs:259) you use reflection to get a constructor for the type provided. If this type is a struct, this doesn't seem to work.

I swapped out the entirety of that method with...

  1. Activator.CreateInstance(type);

..and everything seems to work fine for structs and classes. Was there a reason you went down the constructor reflection route instead of using Activator?

ArenMook

  • Administrator
  • Hero Member
  • *****
  • Thank You
  • -Given: 337
  • -Receive: 1171
  • Posts: 22,128
  • Toronto, Canada
    • View Profile
Re: TNSerializer structs
« Reply #1 on: June 18, 2014, 08:35:56 PM »
Two reasons pretty much. First was to be consistent with the Create (this Type type, int size) function below. The constructor gets cached so there is no lookup in the future. And second -- I'm not too familiar with the Activator. If you say it works, I'll certainly give it a shot. Can it be used with the other function too?

Simie

  • Newbie
  • *
  • Thank You
  • -Given: 0
  • -Receive: 0
  • Posts: 25
    • View Profile
Re: TNSerializer structs
« Reply #2 on: June 19, 2014, 05:41:12 AM »
You can pass in parameters to Activator.CreateInstance, so it could be used for the other function. The only difference is that it would throw an exception if a constructor with the provided parameter signature is not found, instead of falling back on the default constructor or returning null, like the current implementation.

But, assuming that's not a problem, the two methods could be replaced with just

  1.         /// <summary>
  2.         /// Create a new instance of the specified object.
  3.         /// </summary>
  4.  
  5.         static public object Create (this Type type)
  6.         {
  7.                 return Activator.CreateInstance(type);
  8.         }
  9.  
  10.         /// <summary>
  11.         /// Create a new instance of the specified object.
  12.         /// </summary>
  13.  
  14.         static public object Create (this Type type, int size)
  15.         {
  16.                 return Activator.CreateInstance(type, size);
  17.         }

Although, I haven't tested the performance of Activator vs invoking the constructor via reflection.

ArenMook

  • Administrator
  • Hero Member
  • *****
  • Thank You
  • -Given: 337
  • -Receive: 1171
  • Posts: 22,128
  • Toronto, Canada
    • View Profile
Re: TNSerializer structs
« Reply #3 on: June 19, 2014, 07:19:38 PM »
That's a simple matter of wrapping them in a try/catch block though, which is perfectly fine.

Well, let me know if you run into any issues with this approach as it certainly seems cleaner to me. I'll keep an eye on it myself.