473,597 Members | 2,045 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Type alias in C#

Maybe I'm stupid or maybe I am missing the obvious, but I can't find a way
to define a type alias in C# for primitive types (class and interfaces I can
inherit from, no problem). I.e I want to declare a type that is an alias
for, say, int. Conceptually, this is what I want to do:

public MyIntType = int; // won't compile

Anyone knows how to do this?

--
Regards, Peter
Nov 7 '06 #1
59 12225
On a class-file -by- class-file basis you can use (at the top)

using MyIntType = System.Int32;
I.e I want to declare a type that is an alias for, say, int
Well, which do you want to declare: a type or an alias? They are mutually
exclusive. You can't subclass a struct, however.

Marc
Nov 7 '06 #2
Well, which do you want to declare: a type or an alias? They are mutually
exclusive. You can't subclass a struct, however.
What is the difference in C#? In Delphi (where I have the most experience),
you create an alias by doing:

type
MyIntType = integer;

and a new type deriving from another type with:

type
MyIntType = type integer;

I'd be interested knowing the different options available in C#

--
Regards, Peter
Nov 7 '06 #3
Well, in the "class" case, the two syntax demos would be

using SomeAlias = Full.Namespace. To.BaseClass;

vs.

class SomeClass : BaseClass {}

A: The first (alias) is purely a compiler trick *within a single source
file*, to allow two things:
1: (more commonly) to avoid name conflicts within a file without having to
use fully qualified names, e.g. you have a custom class called (bizarrely)
XmlDocument, and you are using System.Xml, so you might alias one of the two
(or both), e.g.
using MyXmlDocument = My.Namespace.Xm lDocument;

this now means that in your class file you can use
MyXmlDocument doc = new MyXmlDocument() ;
etc without the risk of conflicts, *but* the compiled IL only knows about
My.Namespace.Xm lDocument.

2: (less common) to allow the programmer to change the backing type.
Sometimes generics can help, but note that generics do not respect
arithmetic (or other) operators. So if you weren't sure if you needed long
or int, you could use
using SomeAlias = System.Int32;
and then
SomeAlias value = 0;
value += 5;
etc
And if you change your mind later you can change just the alias to Int64.
*If* all the operations are still supported, then it will compile and work,
(but may break your interfaces).

B: the second (inheritance) defines a new type in your assembly inherited
from the old. This will allow automatic casting in one direction only, and
*possibly* won't change the behaviour significantly, but is not a good idea.
As well as being messy, it won't work with interface, static, sealed,
struct, etc.

Marc
Nov 7 '06 #4
"Marc Gravell" <ma**********@g mail.comwrote in message
news:OT******** ******@TK2MSFTN GP04.phx.gbl...
B: the second (inheritance) defines a new type in your assembly inherited
from the old. This will allow automatic casting in one direction only, and
*possibly* won't change the behaviour significantly, but is not a good
idea. As well as being messy, it won't work with interface, static,
sealed, struct, etc.
It also won't work with value types (System.Double, System.Int, System.Array
etc.) as they cannot be inherited from. The OP was talking about the [very
nice] Delphi language feature called 'type identity' which means the ability
to create a completely new value type based on one of the existing value
types. AFAIK, this can't be done in C#; you're stuck with using only the
predefined value types.

Chris.
Nov 7 '06 #5
He asked what the options were; I thought I laid out the options, and yes:
you are right: none of them include what he wants to do. But I never implied
that they would.

Out of interest, what (in Delphi) does this give you? It's been quite a
while since my last object-pascal days... can you add methods etc? If so,
then (looking to the future) possibly the C# 3.0 extension functions may be
of interest. But no use today.
It also won't work with value types...
Hence "struct" in that list.

Perhaps the "other other" alternative is to declare a struct that
encapsulates the required type, and provide an implicit cast operator in
both directions, plus any other operators etc that are needed (oh for some
static inheritance ;-p). A bit more messing than the OP would no-doubt want
(coming from the Delphi route), but achievable. I've done it many times.

Oh, and System.Array is a reference type.

Marc
Nov 7 '06 #6
Marc Gravell wrote:
He asked what the options were; I thought I laid out the options, and
yes: you are right: none of them include what he wants to do. But I
never implied that they would.

Out of interest, what (in Delphi) does this give you? It's been quite
a while since my last object-pascal days... can you add methods etc?
If so, then (looking to the future) possibly the C# 3.0 extension
functions may be of interest. But no use today.
In a nutshell, it gives you the same thing that having Enums be distinct
types gives you - better error detection at compile time since mixing values
and variables from different domains without coersion will cause errors.

-cd
Nov 7 '06 #7
Thanks, Marc and Cristopher.

It's funny how MS has gone from typedef'ing everything in sight in C/C++ to
creating a language that doesn't allow it at all. This isn't critical to me,
but it would have been nice to be able to define something like

public Hwnd = IntPtr;

to make it more obvious what is expected when declaring method parameters
and interop signatures.

--
Regards, Peter
Nov 7 '06 #8
Cheers - good explanation

[drifts back over projects past... ahh... now I remember ;-p]

Marc
Nov 7 '06 #9
"Marc Gravell" <ma**********@g mail.comwrote in message
news:eu******** ******@TK2MSFTN GP04.phx.gbl...
He asked what the options were; I thought I laid out the options, and yes:
you are right: none of them include what he wants to do. But I never
implied that they would.
OK.
Out of interest, what (in Delphi) does this give you?
The ability to easily define your own value types.
>It's been quite a while since my last object-pascal days... can you add
methods etc?
Not using that particular syntax route, no.
>If so, then (looking to the future) possibly the C# 3.0 extension
functions may be of interest. But no use today.
Possibly.
>It also won't work with value types...
Hence "struct" in that list.
Not all value types are structures, for example, enum.
Perhaps the "other other" alternative is to declare a struct that
encapsulates the required type, and provide an implicit cast operator in
both directions, plus any other operators etc that are needed (oh for some
static inheritance ;-p). A bit more messing than the OP would no-doubt
want (coming from the Delphi route), but achievable. I've done it many
times.
Sure you can. Hey, we could all program in assembly and notepad ;-)
Oh, and System.Array is a reference type.
Yup, you're right. You can't inherit from it though.

Chris.
Nov 7 '06 #10

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

Similar topics

16
4438
by: David Ford | last post by:
I have a macro that I use across the board for freeing ram. I'd like to clean up my code so I don't get these warnings. #define sfree(x) _internal_sfree((void **)&x) #define _internal_sfree(x) ({ if(x && *x) { free(*x); *x=NULL; } }) void somefunction() { char *x = malloc(10); int *y = malloc(10);
26
3108
by: Adam Warner | last post by:
Hello all, I'm very new to C but I have a number of years of Common Lisp programming experience. I'm trying to figure out ways of translating higher order concepts such as closures into C. The code will not be idiomatic C. GCC has an extension to ISO C that permits nested functions: <http://gcc.gnu.org/onlinedocs/gcc/Nested-Functions.html> For implementing closures they have a serious limitation:
2
1262
by: Scott Ribe | last post by:
Here's my issue: Data comes in and is inserted into the database automatically, into a base table A. Later a human looks at the records, fills in some data, and now the records are assigned to some derived table, B or C. In some cases there is no way for the software to know at import time which derived type the data actually is (that determination requires someone to examine an image). 1) Is there any way to change a row of table A...
6
2606
by: Maxim | last post by:
Hello, everybody! I'd like to make global type alias. If I used c++ I would write the following code to create a global type alias: typedef SomeType MyAlias; I've found that using keyword could be used to make type/namespace aliases.
669
25773
by: Xah Lee | last post by:
in March, i posted a essay “What is Expressiveness in a Computer Language”, archived at: http://xahlee.org/perl-python/what_is_expresiveness.html I was informed then that there is a academic paper written on this subject. On the Expressive Power of Programming Languages, by Matthias Felleisen, 1990. http://www.ccs.neu.edu/home/cobbe/pl-seminar-jr/notes/2003-sep-26/expressive-slides.pdf
7
1739
by: chaz | last post by:
Hi, * this class is defined in assembly XXXXClsLib : Public class VVDB : inherits DBFuncs ... * Assembly YYYYFwApi has a reference to XXXXClsLib * this class B in YYYYFwApi has an imports stmt : imports XXXXClsLib.VVDB * and this code of class b gives an error Private Function zzz() As String
5
8275
by: Alias | last post by:
Hi - I'm trying to implement a custom RoleProvider based on the SqlRoleProvider. I keep receiving a an error that it can't load type 'MyRoleTest.MyRoleProvider' when trying to load my RoleProvider. However this only occurs after deployment. On my local machine it works fine. So I created the most basic role provider project I could think of. It is below: Imports System.Web.Security
6
1728
by: dillogimp | last post by:
hi This code is taken from a lisp interpreter by Andru Luvisi. typedef struct obj { enum otype type; struct obj *p; // array of pointer, sizeof(obj)=8 } obj; typedef obj * (*primop)(obj *); obj *all_symbols, *top_env, *nil, *tee, *quote,
1
120977
by: Slapo | last post by:
Hello everyone, I could use some help with this function I've created (see below) that runs flawlessly on PostgreSQL 8.3.6 on my development machine but ends with an error on the production server that has PostgreSQL 7.4.8 installed (see below). My function: CREATE OR REPLACE FUNCTION generate_menu(varchar(255), char(2), varchar(255), int, varchar(255), int, int, varchar(255), varchar(255)) RETURNS text AS ' DECLARE -- declarations...
0
7965
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, well explore What is ONU, What Is Router, ONU & Routers main usage, and What is the difference between ONU and Router. Lets take a closer look ! Part I. Meaning of...
0
8271
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8031
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
6686
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development projectplanning, coding, testing, and deploymentwithout human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
5847
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 instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5426
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
3881
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
1493
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1231
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.