Reputation: 197
I'm trying to create a basic Foo class, and would like to duplicate the way a Color works, but I'm having trouble getting my head around it. E.g., I'd like to get this functionality ...
Color color = Color.Red;
for my Foo, and write
Foo x = Foo.y;
On a related note, and if I understand this correctly,
string s = "...";
is the same as
string s = new string("...".ToCharArray())
My questions is, can I define types that act and behave like that, so that I could have something like
Bar w = 1
; which would be the same as Bar w = new Bar(1)
;
Upvotes: 0
Views: 1066
Reputation: 1501043
For the first part of your question, it sounds like you just want static fields or properties, e.g.
public class Foo
{
// A field...
public static readonly Foo MyFunkyFooField = new Foo(...);
// A property - which could return a field, or create a new instance
// each time.
public static Foo MyFunkyFooProperty { get { return ...; } }
}
For the second part, using a string literal is not like calling new string(...)
, because it reuses the same string reference every time. You can't easily come up with your own behaviour like that.
You can create a custom implicit conversion from int
to Bar
, so that
Bar x = 1;
will work... but I would think twice about doing so. Implicit conversions often hurt code readability by hiding behaviour.
Upvotes: 1