[.net] Instantiating Primitive Types
In .NET I have been able to use the ConstructorInfo retrieved from a System.Type via the TypeInitializer property or the GetConstructor() method to instantiate a new object in a generalized "Instantiate" function.
However, I have run into a wall when some of these types are primitives and have no constructor. How could I go about instantiating a uint, for example,if all I have is a System.Type variable that happens to hold the System.UInt32 value? Do I really have to set up an annoying if/else tree and manually check for all the primitive types?
Thanks for any tips you can think of.
Look at Convert.ChangeType, kind of scary, but it might work:
If that does not do it, all of the numeric types have a static MaxValue and MinValue field that you could use to get an instance of the right type.
Type t = typeof(int);object boxedPrim = Convert.ChangeType(12345,t);//boxedPrim.GetType() == typeof(System.Int32);
If that does not do it, all of the numeric types have a static MaxValue and MinValue field that you could use to get an instance of the right type.
Thanks that was helpful, but unfortunately I don't believe this problem will be solved elegantly. There are things beyond primitive types like a DirectX.Vector3 struct for example, and many other types which I haven't thought of yet (which don't support the IConvertible interface) that I will have to manually check for.
I think this is a .NET problem - why can't all types (perhaps implicitly) support a constructor with no arguments? If it were up to me, it would be part of the language specification...
Thanks again.
I think this is a .NET problem - why can't all types (perhaps implicitly) support a constructor with no arguments? If it were up to me, it would be part of the language specification...
Thanks again.
Cool - now we're talking. Thanks, that's exactly what I'm looking for... I just wish I knew what they did inside that function. I wonder if they make use of internal/private .NET functionality, or if they use the System.Reflection functions to do the work...
Thanks very much for the link. That's one hell of a program - I should have looked it up sooner... It showed me this if anyone is interested:
public static object CreateInstance(Type type, bool nonPublic){ object obj1; if (type == null) { throw new ArgumentNullException("type"); } try { RuntimeType type1 = (RuntimeType) type.UnderlyingSystemType; obj1 = type1.CreateInstanceImpl(!nonPublic); } catch (InvalidCastException) { throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "type"); } return obj1;}
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement