casting to type

R

Ron Vecchi

If a have a funtion:

public object MyFCT(string searchOn, System.Type typ){

string foundval;

///foundval is a string pulled from a database
/// How can I cast the string into the supplied System.Type typ
/// and then return the object?

/// Thanks

}
 
M

Martin Dechev

Hi, Ron Vecchi,

You can create an instance of a type with the static method CreateInstance
on the System.Activator class. I don't understand what is the connection
between the string in the DB and the instance or the type.

Hope this helps
Martin
 
R

Ron

I am trying to create a function that will automaticall cast the value and
return it based on the parameter. This way say if the value returned from
the DB (or Xml,Text,.etc) is a string "True" I can call the method and use
it like so:

bool mybool = MyClass.MyFCT("searchString",bool); //excuse my newbyness
The same would go for Int32, Int16, DateTime, Double......

I am tring to wrap all the converion in one method without creating a method
for each poosible type.

Thanks!

Ron
 
M

Martin Dechev

You know the return type at compile time. I don't see your point. Why do you
want to avoid

bool.Parse(string)

or

Convert.ToBoolean(string)

?

Greetings
Martin
 

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

Members online

Forum statistics

Threads
473,733
Messages
2,569,440
Members
44,832
Latest member
GlennSmall

Latest Threads

Top