Unsafe!
I was trying to create a constructor with an undefined number of parameters, because my PhysicsDynamicClass parameter list was looking like it was becoming unwieldy.Well, turns out you can do something like this with C# using the params keyword. Excellent I thought and off I went to write the constructor.
I started by converting my PhysicsSimpleConstructor with just two parameters. And this is how it looked like
public CPhysicsSimple(params object[] list)
{
Position = (Vector2)list[0];
Rotation = (float)list[1];
}
So I build it, compiled it, and I was hoping that it would be awesome. But I ran into a stupid problem, the way I pass the paramenter when using the constructor.
CPhysicsDynamic physicsComponent = new CPhyisicsDynamic(new Vector2(10,10), 0);
looks fine right? but at runtime C# reads reads the second parameter I passed to the constructor as an integer, and when I do the Casting from object{int} to float (see line three of the first code snippet), C# just can’t do it. WTF?
Which means I need to remember to do this:
CPhysicsDynamic physicsComponent = new CPhyisicsDynamic(new Vector2(10,10), 0f);
And then everything works fine. See the difference? No? Look Harder! Yes that little “f” there After all my parameters and all of the sudden my code became unsafe.
Back to the drawing board.
[UPDATE]
I found a solution for the casting problem. I can use:
Convert.ToSingle(list[1]);
and that will work. That does not make the Constructor less dangerous though.
1 Comment
Other Links to this Post
RSS feed for comments on this post. TrackBack URI
By Marcel Jackwerth, February 21, 2010 @ 2:56 pm
I don’t really know why, but I developed some hatred for constructors during last year. I found myself starting to use “Object Initializers” more often (available since C# 3.0, see http://weblogs.asp.net/dwahlin/archive/2007/09/09/c-3-0-features-object-initializers.aspx ).
Just if you didn’t know – there are a lot of C# devs who missed that feature.