Type casts

I

illegal.prime

Hi all, I have a class that holds a member of type object. This member
could end up being:
uint
int
long
ulong

and possibly some other int types I haven't mentioned. I also provide
secondary constructor that accepts the type as a parameter and stores
it in another member - i.e.:
Foo (Type type)
{
// other code
mType = type;
}

In a subsequent method, I end up doing this:
if (mType == typeof(int))
mInternal = Convert.ToInt32(external.Text);
else if (mType == typeof(uint))
mInternal = Convert.ToUInt32(external.Text);
....
Ideally I would rather do something like this:
mInternal = (mType) external.Text;

Any chance there is an alternate way to do this since the above doesn't
work.

After writing all of that I just noticed that there is a member in
Convert called ChangeType that does exactly what I want - by using it
thusly:
mInternal = Convert.ChangeType(external.Text, mType);

If anyone has anything else they want to add - please do so. I.E. if
my usage is improper/bad or if the basic issue I'm encountering could
be solved in a better way.

Thanks,
Novice
 
J

joao_a_costa

You should use enumeration that can simplify your life and the person
who uses the class:

private enum Types
{
Uint = uint,
Int = int
Long = long
}

(e-mail address removed) escreveu:
 
T

Tom Spink

You should use enumeration that can simplify your life and the person
who uses the class:

private enum Types
{
Uint = uint,
Int = int
Long = long
}

(e-mail address removed) escreveu:

Hi Joao,

I'm afraid that's not valid syntax.
 
?

=?ISO-8859-1?Q?G=F6ran_Andersson?=

As I gather it, mType contains the actual type of the value you have put
in the object? Then you can just do like this:

mInternal = external.Text;

The ChangeType method doesn't do anything at all, as you are converting
the object the same type as it already is.
 
I

illegal.prime

Not quite - the conversion is necessary since as the property on the
external object implies it is just returning a string. So I need to
convert it to the appropriate type.

Novice
 
G

Guest

I don't know what you're using this for but it sounds like a prime candidate
for generics.

Define your class as Foo<T> and use Convert.ChangeType(externalText, T).
 
I

illegal.prime

Generics are .Net 2, right?

If not, then I guess I should start using them - otherwise, I'm not
allowed to upgrade since we don't have a way to upgrade our user base's
version of .Net.

Thanks,
Novice
 

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