Daniel J. Harrington
Daniel J. Harrington

Reputation: 13

Can a class return a static instance of itself? (in c#)

Right now my class is set up as:

enum Unit{Inches,Centimeters};

Later on I have a step that sets all of the properties of each of these units into my classes instance variables. For example:

int unitBase; //10 for metric, 16 for american
int label;
switch(unit)
{
    case Unit.Inches: unitBase = 16; unitLabel = "\"";break;
    case Unit.Centimeters: unitBase = 10; unitLabel = "cm";break;
}

I would rather store this all in a Unit class or struct. Then, I would like to be able to access it in the same way you access colors, for example. You say Color.Blue for a blue color, I would like to say Unit.Inches for inches... That is why I dont make a unit base class and simply extend it.

I know that there is a way to do this! Could anyone enlighten me?

Thanks!

Upvotes: 1

Views: 1713

Answers (2)

BrokenGlass
BrokenGlass

Reputation: 160922

You can use static properties:

public enum UnitSpecifier{Inches,Centimeters};

public class Unit
{
    int unitBase; //10 for metric, 16 for american
    string unitLabel;

    public Unit(UnitSpecifier unit)
    {
        switch (unit)
        {
            case UnitSpecifier.Inches: unitBase = 16; unitLabel = @"\"; break;
            case UnitSpecifier.Centimeters: unitBase = 10; unitLabel = "cm"; break;
        }
    }

    public static readonly Unit Inches = new Unit(UnitSpecifier.Inches);
}

Upvotes: 8

mgronber
mgronber

Reputation: 3419

public struct Unit {
    public static readonly Unit Inches = new Unit(16, "\"");
    public static readonly Unit Centimeters = new Unit(10, "cm");

    private readonly int _unitBase;
    private readonly string _unitLabel;

    static Unit() { }

    private Unit(int unitBase, string unitLabel) {
        this._unitBase = unitBase;
        this._unitLabel = unitLabel;
    }

    public int UnitBase {
        get { return this._unitBase; }
    }

    public string UnitLabel {
        get { return this._unitLabel; }
    }
}

Upvotes: 1

Related Questions