Types depending on other types

A

Axel Dahmen

Hi,

I want to define a local variable having a type defined somewhere else. Is
this possible in C#?


Here's a more detailed description of what I'm about:

Given a member somewhere in a class:

class C
{public int m;}


In some function I want do define a variable having exact the type of the
member defined above without actually knowing that type, somewhat like:

void f()
{C::m v;}


So if I change the class definition to:

class C
{public double m;}

the local variable v in my function f() becomes of the same type -- double.


TIA,
Axel Dahmen
 
N

Nicholas Paldino [.NET/C# MVP]

Axel,

Quite simply, you can't do that. What you would have to do is create a
variable of type object, and then store the contents of the field in there,
or keep track of the type through reflection.

Hope this helps.
 
G

Guest

I won't delve into WHY you want to do this - it seems a bit fishy to me... But...

You could do this in C++ with a typedef but C# doesn't have a "typedef" keyword... You could do this in C++ using templates but C# doesn't have templates {yet}...

You could be adventurous and write code to the Whidbey Beta 2.0 .NET Framework {2+ gig download from MSDN}...
You could wait until Whidbey is released and V2.0 of the Framework is standard...

--Richard
 
A

Axel Dahmen

Thanks to all of you.

I don't want to use "object" because I think it has some drawbacks to use
it. It's not typesafe and it bears packaging as well as unnecessary
conversion overhead.

My problem was (is), that I've been using byte as a "percentage" member
property throughout my program when I realized it should be double to allow
for fractional percentage values. So I had to amend all local variables
storing this value temporarily.

For me it seem logical to write code like "use a type mentioned somewhere
else and don't care what it is as long it provides all necessary operators."
Of course this results in what an object is, but as I mentioned, I prefer
early binding instead of late binding. Reflection is nifty when dealing with
unknown objects but my code knows all the objects at compile time.

Thanks for enlighting me, Richard.

Best regards,
Axel Dahmen


------------------------------
Richard said:
I won't delve into WHY you want to do this - it seems a bit fishy to me... But...

You could do this in C++ with a typedef but C# doesn't have a "typedef"
keyword... You could do this in C++ using templates but C# doesn't have
templates {yet}...
You could be adventurous and write code to the Whidbey Beta 2.0 .NET
Framework {2+ gig download from MSDN}...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top