473,566 Members | 3,342 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 13329
> 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.c om> wrote in message
news:%2******** ********@TK2MSF TNGP04.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.Nume rator, 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@fed1read 08...
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.c om> wrote in message
news:%2******** ********@TK2MSF TNGP04.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 misunderstandin gs. 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.co m>
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

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

97
27708
by: s | last post by:
Can I do this: #define MYSTRING "ABC" .. .. .. char mychar = MYSTRING; .. .. ..
3
10565
by: theotyflos | last post by:
Hi all, I have the following: /*--- SNIP ---*/ typedef struct Argument_s { char *address; int type;
21
8678
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 defined it as a char variable. I've searched everywhere but I don't seem to find any place that explains how to define this type of data type. The...
11
3634
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 one byte up to 4 byted in mixed order. Now I want to define a structure to overlay it with UNION over the receive buffer for easily access to the...
12
5783
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
3578
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
4222
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 OleDbConnection Dim cmd As OleDbCommand Dim dr As OleDbDataReader
10
3905
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 based on an exisiting one and handled by a compiler. So, actually both things are equivalent? Or are there any special cases where it makes a...
5
2559
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: const char *s = string_mapper<thetype>(); However I do not know the string to be associated with the type at compile time, and will need a way to set...
0
7673
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7584
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8109
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
7953
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
1
5485
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3626
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2085
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1202
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
926
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.