473,545 Members | 2,663 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Type of Type

Hoi there,

I am a Delphi Programer who moved over to C# some months ago. So far I
am really happy with C# and feelt myself confortable quite fast. Just
some advanced questions regarding the type system are left.

One question is the "type of type" issue:

In Delphi (Pascal) I was able to do the following (free translation to
C# pseudocode ;-) ):

// A simple class
public class MyChildPageBase
{
}

// A simple derived class
public class MyChildTasks : MyChildPageBase
{
}

// A specified type of the base class
public type of MyChildPageBase class MyChildPageBase Type;
Instead using Type I then could use this new type like this:

public void CreateChildPage (MyChildPageBas eType childType)
{
ChildBase child = new childType.Creat eInstance();
}

This way the compiler ensured that CreateChildPage () could only be
called with the type of MyChildPageBase or any derived class. Look at
this:

CreateChildPage (MyChildTasks); // <- works well
CreateChildPage (MyChildPageBas e); // <- works well
CreateChildPage (int); // <- compiler error

I think I can use the IS operator in C# to ensure types at runtime but
I'd like to check it at compile-time so I already get compiler-error
for the last line of the above code.

Does anybody have an idea if and how I can do this in C#?

Cheers,
Marc

Jul 5 '06 #1
10 1877
Well, if I understand what you are doing, then in 2.0 generics may be the
answer:

public void CreateChildPage <T>() where T : MyChildPageBase , new()
{
T child = new T();
// whatever else, perhaps returning child with the sig. "public T
Create..."
}

Then call CreateChildPage <MyChildTasks>( ) or
CreateChildPage <MyChildPageBas e>() will be fine, but CreateChildPage <int>()
will fail at compile time.

Is this what you mean?

Marc
Jul 5 '06 #2
public void CreateChildPage (Type type)
{
// now you can use IS
if(type is MyChildTasks)
return new type.CreateInst ance();

if(type is MyChildPageBase )
return new type.CreateInst ance();

throw new Exception(...);
}
However, I think it would be better to have it as you did. As a
programmer, I would rather know at compile time if I'm passing an
incorrect type vs. finding out at runtime that I goofed.


On 5 Jul 2006 05:41:07 -0700, ma**@idev.ch wrote:
>Hoi there,

I am a Delphi Programer who moved over to C# some months ago. So far I
am really happy with C# and feelt myself confortable quite fast. Just
some advanced questions regarding the type system are left.

One question is the "type of type" issue:

In Delphi (Pascal) I was able to do the following (free translation to
C# pseudocode ;-) ):

// A simple class
public class MyChildPageBase
{
}

// A simple derived class
public class MyChildTasks : MyChildPageBase
{
}

// A specified type of the base class
public type of MyChildPageBase class MyChildPageBase Type;
Instead using Type I then could use this new type like this:

public void CreateChildPage (MyChildPageBas eType childType)
{
ChildBase child = new childType.Creat eInstance();
}

This way the compiler ensured that CreateChildPage () could only be
called with the type of MyChildPageBase or any derived class. Look at
this:

CreateChildPag e(MyChildTasks) ; // <- works well
CreateChildPag e(MyChildPageBa se); // <- works well
CreateChildPag e(int); // <- compiler error

I think I can use the IS operator in C# to ensure types at runtime but
I'd like to check it at compile-time so I already get compiler-error
for the last line of the above code.

Does anybody have an idea if and how I can do this in C#?

Cheers,
Marc
Jul 5 '06 #3
Turn on compiler warnings ;-p

The variable "type" is declared as a "Type", so can never be (inherit from)
either MyChildTasks or MyChildPageBase , so "is" is not the right test here;
to replace your "is" tests you would need one of (depending on exact
behaviour wanted):

if(type == typeof(MyChildT asks)) // strict match
OR
if(type.IsAssig nableFrom(typeo f(MyChildTasks) )) // exact or subclass
OR
if(type.IsSubcl assOf(typeof(My ChildTasks))) // strict subclass

The actual creation would look like:
type.GetConstru ctor(Type.Empty Types).Invoke(n ull);
Did you mean "new {concrete class}"? Note the above usage also removes the
need for the tests in the first place, but only validates at runtime.

All very messy, eh? However, in 2.0 generics is a much better solution. See
previous post.

Marc
Jul 5 '06 #4
Jeff Shepler wrote:
public void CreateChildPage (Type type)
{
// now you can use IS
if(type is MyChildTasks)
return new type.CreateInst ance();

if(type is MyChildPageBase )
return new type.CreateInst ance();

throw new Exception(...);
}
However, I think it would be better to have it as you did. As a
programmer, I would rather know at compile time if I'm passing an
incorrect type vs. finding out at runtime that I goofed.


On 5 Jul 2006 05:41:07 -0700, ma**@idev.ch wrote:
>>Hoi there,

I am a Delphi Programer who moved over to C# some months ago. So far I
am really happy with C# and feelt myself confortable quite fast. Just
some advanced questions regarding the type system are left.

One question is the "type of type" issue:

In Delphi (Pascal) I was able to do the following (free translation to
C# pseudocode ;-) ):

// A simple class
public class MyChildPageBase
{
}

// A simple derived class
public class MyChildTasks : MyChildPageBase
{
}

// A specified type of the base class
public type of MyChildPageBase class MyChildPageBase Type;
Instead using Type I then could use this new type like this:

public void CreateChildPage (MyChildPageBas eType childType)
{
ChildBase child = new childType.Creat eInstance();
}

This way the compiler ensured that CreateChildPage () could only be
called with the type of MyChildPageBase or any derived class. Look at
this:

CreateChildPa ge(MyChildTasks ); // <- works well
CreateChildPa ge(MyChildPageB ase); // <- works well
CreateChildPa ge(int); // <- compiler error

I think I can use the IS operator in C# to ensure types at runtime but
I'd like to check it at compile-time so I already get compiler-error
for the last line of the above code.

Does anybody have an idea if and how I can do this in C#?

Cheers,
Marc
Hi Jeff,
if(type is MyChildTasks)
I'm afraid that won't work. You need to do this:

///
if ( type == typeof( MyChildTasks ) )
///

The reason being, 'is' tests that the instance of an object is of the given
type, the instance of 'type' will always be a System.Type, never
a 'MyChildTasks'.

Also, your method returns void, so your return statements are invalid.

You'd need to rewrite your method to something like this:

///
MyChildPageBase CreateChildPage ( Type type )
{
if ( type == typeof( MyChildTasks ) )
return new MyChildTasks();
else if ( type == typeof( MyChildPageBase ) )
return new MyChildPageBase ();

throw new Exception( "Given type is invalid" );
}
///

--
Hope this helps,
Tom Spink
Jul 5 '06 #5
ma**@idev.ch wrote:
One question is the "type of type" issue:
I think you're talking about Delphi metaclasses, i.e.:

type
TMyClass = class of TMyObject;

The closest analogue is Type, and the create you're looking for could
either be Activator.Creat e(Type) or (if you need fine control)
Type.GetConstru ctor() followed by ConstructorInfo .Invoke().
I think I can use the IS operator in C# to ensure types at runtime but
I'd like to check it at compile-time so I already get compiler-error
for the last line of the above code.

Does anybody have an idea if and how I can do this in C#?
There is no exact equivalent, which would be type variable which is also
bounded (i.e. restricted to a particular class and all its descendants)
and statically type-checked as such.

-- Barry

--
http://barrkel.blogspot.com/
Jul 5 '06 #6
hey guys, thanks a lot for all thouse fast replies!!! i am impressed!
I think you're talking about Delphi metaclasses, i.e.:

type
TMyClass = class of TMyObject;
yes, exactly. maybe its better if i write some more pascal-sample in
here es there seems to be other pascal-experts around there ;-)

the pascal-pattern i try to get into c# is the following:

type

TMyObj1 = class
end;

TMyObj2 = class (TMyObj1)
end;

TMyObj1Class = class of TMyObj1;

function DoSomething(var myObj: TMyObj1; myObjClass: TMyObj1Class):
boolean;
begin
if not assigned(myObj) then begin
myObj := myObjClass.Crea te();
end;
end;

Now use this function/method like this:

var
myObj1: TMyObj1;
myObj2: TMyObj2;
begin
DoSomething(myO bj1); // compiles well
DoSomething(myO bj2); // compiles well
DoSomething(int eger); // compiler error !!
DoSomething(str ing); // compiler errer !!

hope i will not be kicked here because of the pascal instead of c#
;-))))

using IF-statements will work at runtime, yet but not at compile-time.
i d' like to know at compile-time where i (or any other developer ;-) )
- used the wrong types so i have to run all the code to get exceptions.

from my point of view the generic sample is the one getting closest as
then the compiler will do the type-checks. but i am having problems
gettings this to compile as i get a tricky compiler-error:

"Cannot convert type 'ChildTask to 'ChildBase' "

it seems i got something wrong. hmm... have to "investigat e" a little
more ;-)

cheers,
marc

Jul 5 '06 #7
Barry Kelly wrote:
There is no exact equivalent, which would be type variable which is also
bounded (i.e. restricted to a particular class and all its descendants)
and statically type-checked as such.
didn't get this one. what do you mean by this?

thx, marc

Jul 5 '06 #8
<ma**@idev.ch a écrit dans le message de news:
11************* ********@75g200 0c...legrou ps.com...

| I am a Delphi Programer who moved over to C# some months ago. So far I
| am really happy with C# and feelt myself confortable quite fast. Just
| some advanced questions regarding the type system are left.
|
| One question is the "type of type" issue:
|
| In Delphi (Pascal) I was able to do the following (free translation to
| C# pseudocode ;-) ):
|
| // A simple class
| public class MyChildPageBase
| {
| }
|
| // A simple derived class
| public class MyChildTasks : MyChildPageBase
| {
| }
|
| // A specified type of the base class
| public type of MyChildPageBase class MyChildPageBase Type;
|
|
| Instead using Type I then could use this new type like this:
|
| public void CreateChildPage (MyChildPageBas eType childType)
| {
| ChildBase child = new childType.Creat eInstance();
| }
|
| This way the compiler ensured that CreateChildPage () could only be
| called with the type of MyChildPageBase or any derived class. Look at
| this:
|
| CreateChildPage (MyChildTasks); // <- works well
| CreateChildPage (MyChildPageBas e); // <- works well
| CreateChildPage (int); // <- compiler error
|
| I think I can use the IS operator in C# to ensure types at runtime but
| I'd like to check it at compile-time so I already get compiler-error
| for the last line of the above code.

If you are using C# 1.1, then the only way to do this is to create your own
"metaclass" with a Create method that returns instances of the correct type.

I wrote an article for the UK Developers Group on this subject

http://www.prototypical.co.uk/pdf/C%...l%20delphi.pdf

As Marc says, if you are using C# 2.0, then generics are your friend.

Joanna

--
Joanna Carter [TeamB]
Consultant Software Engineer
Jul 5 '06 #9
ma**@idev.ch wrote:
Barry Kelly wrote:
There is no exact equivalent, which would be type variable which is also
bounded (i.e. restricted to a particular class and all its descendants)
and statically type-checked as such.

didn't get this one. what do you mean by this?
A Delphi metaclass is a type which refers to a type. So is .NET's
System.Type. The difference with Delphi metaclasses is that they can be
bounded - i.e. limited in a certain way.

The metaclass "TClass" can refer to any Delphi type descending from
TObject, or TObject itself. "TComponentClas s" can only refer to types
descending from TComponent, or TComponent itself - it is bounded, or
restricted to a particular class (TComponent) and all its descendants
(TControl, etc...).

There is no exact equivalent in C# or .NET, and it isn't possible to
write a statically checked version in C# 2.0 - i.e. one that caused a
compile-time error when you try to assign the wrong type into the
variable. For example, you'll get a compile-time error in Delphi if you
try to assign TStringList into a variable of type TComponentClass . This
is not possible right now with C#.

(As a side note: if C# ever exposes the variance capabilities of the
underlying CLI, it would actually be possible to do something fairly
close to this using generics. As it is, I can think of a couple of ways
of hacking something up in IL, but it would be a pain to maintain.)

-- Barry

--
http://barrkel.blogspot.com/
Jul 5 '06 #10

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

Similar topics

21
4498
by: Batista, Facundo | last post by:
Here I send it. Suggestions and all kinds of recomendations are more than welcomed. If it all goes ok, it'll be a PEP when I finish writing/modifying the code. Thank you. .. Facundo
6
2680
by: S.Tobias | last post by:
I'm trying to understand how structure type completion works. # A structure or union type of unknown # content (as described in 6.7.2.3) is an incomplete type. It # is completed, for all declarations of that type, by ^^^ # declaring the same structure or union tag with its defining # content ...
0
1764
by: Chris Fink | last post by:
When I am consuming a webservice, an object has an undefined value (inq3Type.Call3Data). I do not completely understand why this is happening and apologize for the vague question. My assumption is that the WSDL is defined incorrectly and .NET cannot parse the types. Any help is greatly appreciated! CustDDGSvc ws = new CustDDGSvc();...
1
8691
by: Rob Griffiths | last post by:
Can anyone explain to me the difference between an element type and a component type? In the java literature, arrays are said to have component types, whereas collections from the Collections Framework are said to have an element type. http://java.sun.com/docs/books/jls/second_edition/html/arrays.doc.html
669
25600
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....
3
2818
by: john | last post by:
Hi to All To demonstrate: public class MyBaseGenericClass<T> { } public class MyGenericClass1<T: MyBaseGenericClass<T> {
7
7800
by: Sky | last post by:
I have been looking for a more powerful version of GetType(string) that will find the Type no matter what, and will work even if only supplied "{TypeName}", not the full "{TypeName},{AssemblyName}" As far as I know yet -- hence this question -- there is no 'one solution fits all', but instead there are several parts that have to be put...
9
3850
by: weirdwoolly | last post by:
Hopefully someone will be able to help. I have written a stored procedure in C++ called from a Java test harness to validate the graphic data types in C++ and their use. I have declared the vargraphic input parameters along the following lines in i_vargraphic100 vargraphic(100) and they are populated from String's in java.
5
3159
by: JH | last post by:
Hi I found that a type/class are both a subclass and a instance of base type "object". It conflicts to my understanding that: 1.) a type/class object is created from class statement 2.) a instance is created by "calling" a class object.
3
17097
by: amanjsingh | last post by:
Hi, I am trying to implement Java Web Service using Apache Axis2 and Eclipse as a tool. I have created the basic code and deployed the service using various eclipse plugin but when I try to invoke the service using client stub, I get this error... Exception in thread "main" java.lang.Error: Unresolved compilation problems: org.apache cannot...
0
7490
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
7425
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
7682
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. ...
0
7935
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
7780
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
5351
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
3479
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...
1
1911
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
0
734
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.