Just said:
There are some situations, not for
everyday use, but some, when we can use the power of the compiler to define
our own types and work with them as predefined types.
Ahh... that's different. I thought that you wanted to "rename" existing
types, which is evil. ;-)
If you want to make your own "primitive" types, types that _act_ like
int or double, then look into C# structs. What you want is to declare a
"struct", not a "class". In C# a struct is a _value type_, which means
that it acts like int or double: it is copied on every assignment, and
"lives" on the stack or in the same area as other "primitive" members
of class state.
(If I may say so, it's refreshing to finally be able to post in this
group and _recommend_ that someone use struct, rather than constantly
steering people away from its many abuses.)
For example, I've written a couple of structs: I have a Fraction
struct, which allows me to do mathematics, assignments, and other such
things with Fractions as though they were decimals, ints, or doubles. I
also have a Measure class that combines a decimal value with a unit of
measure, and allows me to perform mathematics on, for example, lengths
with appropriate conversions going on in the background.
Some tips if you're going to venture into writing your own struct:
1. It's a good idea to make the struct immutable. That is, its
properties have no setters and its methods do not modify its state but
return new copies. If you want to change a property in the struct, you
have to create a new one. So, for example, it's generally a poor idea
to allow this, if Fraction is a struct:
Fraction f = new Fraction(5, 7);
f.Denominator = 9;
If you make Fraction immutable, you force people to do this instead:
Fraction f = new Fraction(5, 7);
f = new Fraction(f.Numerator, 9);
While the former code looks tidier, there are resons why it is "bad":
the reasons have to do with how structs act when boxed, and how they
act as results returned by methods or properties. Making them immutable
makes them slightly less convenient, but also much less confusing.
2. Similarly, any methods in your struct should return a new copy of
the struct, not modify the existing copy, so you don't want this:
f.Normalize();
but rather this:
f = f.Normalize();
3. You should override both the Equals method and the == operator (as
well as all of the other comparison operators). If your struct
represents a quantity that could logically be added, subtracted, etc,
then you should override the mathematical operators as well.
Finally, sorry about the earlier, testy response, but I got the wrong
idea from your original post: I thought that you wanted to play "macro
grames" in C# the way that one can in C or C++ and I cringed. I'm glad
that you've found a real use for structs!