By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,200 Members | 1,568 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,200 IT Pros & Developers. It's quick & easy.

Define my own data type

P: n/a
All,

It was possible before in Pascal, C++, etc. to define our custom data type
or redefine the existing type, like in Turbo Pascal we could assume that
shortint is int and use all references to shortint like all these variables
became int.

How can we define our own user data type in C# is we can?

Just D.
Jun 23 '06 #1
Share this Question
Share on Google+
12 Replies


P: n/a
> It was possible before in Pascal, C++, etc. to define our custom data type
or redefine the existing type, like in Turbo Pascal we could assume that
shortint is int and use all references to shortint like all these
variables became int.

How can we define our own user data type in C# is we can?


Can you cite a C++ example (probably using a macro or typedef if I
understand you). Note BTW that a class *is* a custom data type.
Jun 23 '06 #2

P: n/a
Just D wrote:
It was possible before in Pascal, C++, etc. to define our custom data type
or redefine the existing type, like in Turbo Pascal we could assume that
shortint is int and use all references to shortint like all these variables
became int.

How can we define our own user data type in C# is we can?


In general terms, defining a new class in C# _is_ defining a new type.

If, however, you mean that you want to define an "alias" for an
existing data type, so that, for example, all places in your code that
say

short x;

and suchlike use the int type instead of the "short" that is written
there, then no, you cannot do that in C#. Furthermore, it's a great
feature (or un-feature) that you can't do that. In 20 years of C
programming I saw this feature (ab)used only once, and it took me an
hour of staring at the code and debugging, wondering why it was acting
so #$&*$@ weird, before I looked inside a header file and found that
some jackass had redefined a basic type in this way. Fortunately he no
longer worked for the company, or I would have been honour-bound to
have killed him and mounted his head on a pike or something like that.

I'm very happy that C# doesn't let people do crap like redefine
existing, basic types.

However, if you want to define a brand new type, then just declare a
new class and there you have it.

Jun 23 '06 #3

P: n/a
Just D wrote:
All,

It was possible before in Pascal, C++, etc. to define our custom data type
or redefine the existing type, like in Turbo Pascal we could assume that
shortint is int and use all references to shortint like all these
variables became int.

How can we define our own user data type in C# is we can?

Just D.


Hi Just D,

If you define a class, and overload the implicit conversion operator, you
can 'fake' it.

///
public class MyIntClass
{
private int _a;

public MyIntClass ( int a )
{
_a = a;
}

public int Value
{
get { return _a; }
}

public static implicit operator MyIntClass ( int a )
{
return new MyIntClass( a );
}

public static implicit operator int ( MyIntClass a )
{
return a._a;
}
}
///

So you can now do this:

///
MyIntClass test1 = 5;
int test2 = test1;
///

If you really want to, that is.

Hope this helps,
-- Tom Spink
Jun 23 '06 #4

P: n/a
Thanks so much, Tom!

But that's actually not what I wanted. I saw many advices on the Internet
that we can define our own types using structure, maybe we can use your way
with the class, but it's not exactly what I was looking for. I wanted to
create my own primitive type for my own convenience. The examples that I
found on the Internet were telling mostly about new XML types and only in
rare cases about C# using structure.

Regarding my previous opponent who spent 20 years in programming...) Well,
I'm not a boy as well, I started writing programs in 1979 and know a little
bit about this procedure. :) If I didn't want to get it for sure I'd never
ask this question in this newsgroup...) 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. I'm not going to argue
with anybody, because walking this way we easily can start complaining about
multiple inheritance and other features that have been ignored in this so
good, convenient, powerful and safe language as C# :) Each stuff has it's
own advantages and disadvantages, we just need to have enough skills and a
good reason for using them. It's not discussible and depends on how do you
personally like these things, can you use them or not, etc. I guess this
thread can be closed with that.

Good luck!

Just D.

"Tom Spink" <ts****@gmail.com> wrote in message
news:%2****************@TK2MSFTNGP04.phx.gbl...
Just D wrote:
All,

It was possible before in Pascal, C++, etc. to define our custom data
type
or redefine the existing type, like in Turbo Pascal we could assume that
shortint is int and use all references to shortint like all these
variables became int.

How can we define our own user data type in C# is we can?

Just D.


Hi Just D,

If you define a class, and overload the implicit conversion operator, you
can 'fake' it.

Jun 23 '06 #5

P: n/a
Just D wrote:
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!

Jun 23 '06 #6

P: n/a
Hi Just D,

While it is not possible to define a "Primitive" (ValueType) in C#, it is
possible in MSIL, which means that you can then use that type in C or
whatever language you please. See the following article:

http://weblogs.asp.net/kennykerr/arc...09/227316.aspx

--
HTH,

Kevin Spencer
Microsoft MVP
Professional Chicken Salad Alchemist

I recycle.
I send everything back to the planet it came from.

"Just D" <no@spam.please> wrote in message
news:WEJmg.439$RD.264@fed1read08...
Thanks so much, Tom!

But that's actually not what I wanted. I saw many advices on the Internet
that we can define our own types using structure, maybe we can use your
way with the class, but it's not exactly what I was looking for. I wanted
to create my own primitive type for my own convenience. The examples that
I found on the Internet were telling mostly about new XML types and only
in rare cases about C# using structure.

Regarding my previous opponent who spent 20 years in programming...) Well,
I'm not a boy as well, I started writing programs in 1979 and know a
little bit about this procedure. :) If I didn't want to get it for sure
I'd never ask this question in this newsgroup...) 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. I'm not going to argue with anybody, because walking this way we
easily can start complaining about multiple inheritance and other features
that have been ignored in this so good, convenient, powerful and safe
language as C# :) Each stuff has it's own advantages and disadvantages, we
just need to have enough skills and a good reason for using them. It's not
discussible and depends on how do you personally like these things, can
you use them or not, etc. I guess this thread can be closed with that.

Good luck!

Just D.

"Tom Spink" <ts****@gmail.com> wrote in message
news:%2****************@TK2MSFTNGP04.phx.gbl...
Just D wrote:
All,

It was possible before in Pascal, C++, etc. to define our custom data
type
or redefine the existing type, like in Turbo Pascal we could assume that
shortint is int and use all references to shortint like all these
variables became int.

How can we define our own user data type in C# is we can?

Just D.


Hi Just D,

If you define a class, and overload the implicit conversion operator, you
can 'fake' it.


Jun 23 '06 #7

P: n/a
>
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.


Would you please elaborate a bit further? I would like to understand why
this is bad. I'm not challenging your advice; I'm just ignorant.

Thanks,
Bill
Jun 23 '06 #8

P: n/a
Bill O'Neill wrote:

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.


Would you please elaborate a bit further? I would like to understand why
this is bad. I'm not challenging your advice; I'm just ignorant.

Thanks,
Bill


It's "bad" because it leads to misunderstandings. Most people reading /
developing code expect variables to act in one of two ways: like
primitive, indivisible types, or like objects (reference types). I'll
use System.Drawing.Point as an example of how mutable structs can be
confusing.

Microsoft chose to make Point a struct, which changes its semantics,
but so long as you understand that it's now a value makes perfect
sense. Unfortunately, they chose to make Point.X and Point.Y settable
properties. I think that they did it for convenience, so that you could
say things like this:

Point p = new Point(5, 4);
p.Y = 6;

and now p contains (5, 6). So far, so good.

However, problems start to crop up when you have Points as property
results in other classes. For example, let's say you have

public class Fubar
{
private Point _p;

public Point TopLeft { get { return this._p; } set { this._p =
value; } }
}

Because Point is mutable, people expect to be able to do things like
this:

Fubar f = new Fubar();
f.TopLeft = new Point(15, 20);
f.TopLeft.X = 20;

I believe that the compiler complains about that last line. Why? Since
Point is a value, the "get" for TopLeft returns a _copy_ of Fubar's _p
on the stack, so modifying the X property of that copy does nothing at
all, because the runtime then throws the copy away, so modifying any of
its fields is useless.

There's no problem from the compiler's point of view: the problem is a
conceptual one: when people read lines like

f.TopLeft.X = 20;

they think "class" or "object", because it's typically reference types
(classes) that have settable fields. It's tricky to remember that this
is a _value_, not a reference type, and so it acts differently.

In .NET 1.1, the same problem cropped up with aggregate structures like
ArrayList:

ArrayList list = new ArrayList();
list.Add(new Point(5, 6));
((Point)list[0]).X = 10;

the last line is a no-op for similar reasons to those above: unboxing
the ArrayList entry yields a _copy_ of the value, and setting the X
property for that copy doesn't affect the original still boxed in the
ArrayList. In order to modify the entry, you have to do this:

list[0] = new Point(10, ((Point)list[0]).Y);

or something similar.

In other words, mutable structs are just plain confusing, and you don't
really need them. For that reason, I prefer to make my structs
immutable.

Jun 23 '06 #9

P: n/a
Kevin Spencer <uc*@ftc.gov> wrote:
While it is not possible to define a "Primitive" (ValueType) in C#, it is
possible in MSIL, which means that you can then use that type in C or
whatever language you please. See the following article:

http://weblogs.asp.net/kennykerr/arc...09/227316.aspx


I'm not entirely sure what you think can't be done in C#. You can't
define your own genuine primitive types (as per framework terminology)
but you can't do that in IL either.

You *can* however define your own value types in C#- just declare them
as "struct" instead of "class".

I suspect I've missed something in terms of what you were trying to say
- care to enlighten me?

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Jun 23 '06 #10

P: n/a
On 22 Jun 2006 20:03:24 -0700, "Bruce Wood" <br*******@canada.com>
wrote:

just a word, bruce...

what do you say about basic types like int32, uint32, int16, uint16
and so on? they are in fact even more readable than the original
one's. In Unix I also found datatypes like this: u8, i8, u16, i16,
u32, i32... unix programmers always tend to write as less as possible
:-)

I agree to you, if someone uses int32 as a 16 bit type, then you have
the right to complain. on the other hand, if you need one hour to
debug a misuse of a data type, which in first sight has another name
than the original ones, then I doubt a bit of your programming skills
at this time ;-)

And yes, I agree to JustD , this C "feature" was one of the first
things I missed in C#.

so long,
noah

Just D wrote:
It was possible before in Pascal, C++, etc. to define our custom data type
or redefine the existing type, like in Turbo Pascal we could assume that
shortint is int and use all references to shortint like all these variables
became int.

How can we define our own user data type in C# is we can?


In general terms, defining a new class in C# _is_ defining a new type.

If, however, you mean that you want to define an "alias" for an
existing data type, so that, for example, all places in your code that
say

short x;

and suchlike use the int type instead of the "short" that is written
there, then no, you cannot do that in C#. Furthermore, it's a great
feature (or un-feature) that you can't do that. In 20 years of C
programming I saw this feature (ab)used only once, and it took me an
hour of staring at the code and debugging, wondering why it was acting
so #$&*$@ weird, before I looked inside a header file and found that
some jackass had redefined a basic type in this way. Fortunately he no
longer worked for the company, or I would have been honour-bound to
have killed him and mounted his head on a pike or something like that.

I'm very happy that C# doesn't let people do crap like redefine
existing, basic types.

However, if you want to define a brand new type, then just declare a
new class and there you have it.


Jun 24 '06 #11

P: n/a
noah <noah@home> wrote:
I agree to you, if someone uses int32 as a 16 bit type, then you have
the right to complain. on the other hand, if you need one hour to
debug a misuse of a data type, which in first sight has another name
than the original ones, then I doubt a bit of your programming skills
at this time ;-)


To me, that just suggests you haven't been in macro hell. When things
end up getting redefined (so that potentially the same name can mean
different things at different points in the same file) life can get
very nasty indeed.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Jun 24 '06 #12

P: n/a
> I agree to you, if someone uses int32 as a 16 bit type, then you have
the right to complain. on the other hand, if you need one hour to
debug a misuse of a data type, which in first sight has another name
than the original ones, then I doubt a bit of your programming skills
at this time ;-)


That was exactly the sort of thing that happened. Someone had created a
macro like this, if I recall correctly (it was a long time ago):

#define int short

I spent an hour or so stepping through the code, trying to figure out
why the code was failing for large values, when everything was stored
in ints which were clearly capable of storing the information.

Anyway, it was something along those lines. Stuff like this, I don't
miss.

Jun 24 '06 #13

This discussion thread is closed

Replies have been disabled for this discussion.