1

I want to have simply structure for store information. My problem is to create inner method that clear stored values.

   public struct GraphValues
   {
        public int min, max, ...;

        public GraphValues(int min, int max, ...)
        {
            this.min = min;
            this.max = max;
            ...
        }

        public static void Clear(this GraphValues values)
        {
            values.min.Equals(null);
            values.max.Equals(null);
            ...
        }
    }

So write new values in this structure is OK,

GraphValues val = new GraphValues()
val.max = 12;
val.min = 1;

but I want to set all structure valueas to null. Calling something like

val.Clear();

Any idea? Thnaks

braX
  • 11,506
  • 5
  • 20
  • 33
okubik
  • 11
  • 1
  • 2
  • I suggest you use mine and Mark's answers together to rewrite this whole thing. – Kon Sep 20 '11 at 12:44

2 Answers2

7
  1. Structs should not be mutable. Make your type a class instead.
  2. To allow null values, use nullable types.
  3. Use properties instead of public fields.

Fixed code:

public class GraphValues
{
     public int? Min { get; set; } 
     public int? Max { get; set; }
     // etc...

     public void Clear()
     {
         Min = null;
         Max = null;
         // etc...
     }
}

I'd also suggest that you consider if it would be better to create a new object instead of setting the fields on an existing object to null:

//val.Clear();           // Don't do this.
val = new GraphValues(); // Just create a new object.
Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
2

Remove the 'static' keyword from the Clear() method definition, so that it's available for each instance of your GraphValues object. Also, no need to pass in parameters - inside the Clear() method you'll have access to all your members. And you want to set them to null, not compare their values to null.

    public void Clear()
    {
        this.min = null;
        this.max = null;
        ...
    }

And why is this a struct anyway? Just use class.

Kon
  • 27,113
  • 11
  • 60
  • 86