473,320 Members | 2,189 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

Define my own data type

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
12 13284
> 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
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
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
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
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
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
>
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
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
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
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
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
> 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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

97
by: s | last post by:
Can I do this: #define MYSTRING "ABC" .. .. .. char mychar = MYSTRING; .. .. ..
3
by: theotyflos | last post by:
Hi all, I have the following: /*--- SNIP ---*/ typedef struct Argument_s { char *address; int type;
21
by: Angel Lopez | last post by:
Sorry if I am too naive, but this is my first post... I have a binary variable (it can contain either a 0 or a 1). Is there any way I can define a data type that uses only 1 bit. So far I have...
11
by: Jürgen Hochwald | last post by:
Hi Maybe this is a simple question, but I don't know how to solve. Background: A weather station connected to the serial port sends data packets. This data packets are containing variables fom...
12
by: Pol Bawin | last post by:
Hi All, Did somebody already define attributes for numerical properties to define value : minima, maxima, a number of decimal, ...? This information would be useful to unify syntax Polo
6
by: Kay | last post by:
Hi all, In vb6, I can define a custom type like this: Private Type uClient sName As String sMonday As Double sMondayHeadCnt As Integer End Type
6
by: bokiteam | last post by:
Hi All, I have this error msg, but I have already import lib, could you please advice? Imports System.Data.OleDb Public Class Form1 Inherits System.Windows.Forms.Form Dim cn As...
10
by: Christian Christmann | last post by:
Hi, what is the difference between a "#define" and typedef? A "#define" is handled by the preprocessor and serves as a name substitude whereas "typedef" is a declaration of a new data type...
5
by: alan | last post by:
Hello world, I'm wondering if it's possible to implement some sort of class/object that can perform mapping from class types to strings? I will know the class type at compile time, like so:...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.