Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make own datatype without new modifier

Tags:

c#

I am trying to make a Money datatype (like int, string) in C#. However I can't seem to work out how to use it without the new Modifier. The class cannot be static as it has to be assigned to. I figured there must be a way, here is the code I have for the class, I may be doing this completely wrong.

public class Money {
    private float _raw;

    public float Raw {
        get {  return _raw;  }
        set {  _raw = value;  }
    }

    public string Pound {
        get {  return "£" + string.Format("{0:0.00}", _raw);  }
    }
} 

Then I have the class I am calling it in and would like to just use:

private Money _money;

Instead of:

private Money _money = new Money();

Sorry if this is a stupid question but I couldn't find anything online nor could I figure it out myself.

like image 556
Josh Hornsbyu Avatar asked Jan 19 '26 11:01

Josh Hornsbyu


2 Answers

You'll have to new it up somewhere. If you don't want to do it in the member declaration, then do it in the class constructor:

public MyClass()
{
     _money = new Money();
}
like image 181
Robert Harvey Avatar answered Jan 22 '26 04:01

Robert Harvey


An alternative solution involves using a factory method of some kind.

public class Money {
    private float _raw;

    public float Raw {
        get {  return _raw;  }
        set {  _raw = value;  }
    }

    public string Pound {
        get {  return "£" + string.Format("{0:0.00}", _raw);  }
    }

    public static Money From(float val) 
    {
        Money x = new Money();
        x.Raw = val;
        return x;
    }
} 

usage:

Money m = Money.From(9.95);

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!