Parker's DevEd Blog

Musings on all software development technologies, and education involving computer science and fraud investigation

Serialize Static Fields

There a lot of things to think about when it comes to serializing static fields, how it will be stored, how it will be reinstated, duplication of data, and design. Although, it usually is a sign of bad design if you are trying to serialize static fields, there are some cases in which you need to. In which cases, some work arounds are way to tedious, for what you are actually trying to do, especially some sort of templating. Well here's one way you can do it.

public class Desk {
   
private static string _manufacturer = "Hard Furniture - {Id}";
   
private static string _serial = "HFSTYLE{Id}";
    private int _id;

    // Properties to serialize static fields
    public string Manufacturer {
        get { return _manufacturer; }
        set { _manufacturer = value; }
    }
    public string Serial {
        get { return _serial; }
        set { _serial = value; }
    }

    // Properties
    public int Id {
        get { return _id; }
        set { _id = value
            SetupLocals();
        }
    }

    private void SetupLocals() {
       
// Assign local based on static
        someLocal = Manufacturer.Replace("{Id}", Id.ToString());
        someLocal2 = Serial.Replace(
"{Id}", Id.ToString());
    }

    // Constructors
    private Stop() { }
    public Stop(int id) {
        Id = _id;
    }
}

Comments

No Comments