[.net] [C#] Simple problem with struct and null value

Started by
8 comments, last by g0nzo 17 years, 1 month ago
Hi, I'm trying to rewrite part of the code that uses a custom class to represent a point to use PointF struct. However I need to calculate this point and if anything goes wrong, null value is assigned to the point object. This way in the next iteration I know that there's no previous point (it's null). However it's impossible to assign null to struct: Cannot convert null to 'System.Drawing.PointF' because it is a value type I could create additional boolean value or just create a class that would be almost exactly the same as PointF struct, but is there some easier way? PointF has IsEmpty property, but it's read-only and it returns true for x=y=0, which is not what I need. Thanks in advance
Advertisement
You could assign it PointF.Empty and check for that, assigning 0,0 is still a valid point so isn't empty.
Thanks, but PointF.Empty indicates that the point has value x=0 and y=0. Thus it doesn't indicate that its values are undefined (empty), like in case of null value, but only that they are 0.
Not sure if this is the right solution but it seems like the easy way to me.

Why not add a bool No_Previous_Call member to your struct? This way you set it true when you would have set the other to null and have it default to false the rest of the time.

Any reason taht would not work?

theTroll
Thanks. I already added boolean value to my main class to indicate whether there's already a point or not and it works. I was just wondering, if there's a simpler solution (without adding new members) - like assigning null value for classes, but for structs.
You're correct, I should have checked the IsEmpty code first, a pointless function that is :D you can do it as TheTroll suggests or derive from PointF and override the IsEmpty accessor.

Actually, if you have a list of points, can't you just remove/not add it from/to the list ?
It almost feels like IRC :)

Actually I have only 2 points - previous and current and calculate difference of their position. The app works fine with the boolean flag and it's impossible to derive from a struct in C# (or is it?), so I'll leave it as it for now.

Thanks again!
If you're using .NET 2.0, just make it a Nullable Type.

System.Drawing.PointF? foo = null;if( !foo.HasValue ){    // no previous point}else{    // calculate with foo.Value or cast to a PointF}
You're right, I have no idea what I was thinking and missed the obvious solution, doh. Nullable types.

PointF? p1 = null;
PointF? p2 = PointF.Empty;

If you're passing these into functions just mark the PointF as a nullable type, PointF? and then you should beable to use null.

Edit: ah crap, pipped to the post again :)
Thank you! It works.

This topic is closed to new replies.

Advertisement