Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# CodeGeneration variable as type

In an existing application, code is generated to perform a cast, like below: (the types are also generated classes, I provide an example with just object and string)

object o;
string s = (string)o;

When o is of type int, an InvalidCastException is thrown. Therefore, I want to change the code into:

object o;
string s = o as string;

and check later on whether string s is null.

The System.CodeDom is used to perform the code generation. The cast is generated using the CodeCastExpression Class.

I cannot find a way to generate the variable as type way... Can someone help me out? Thanks!

like image 397
Peter van Kekem Avatar asked Sep 29 '26 05:09

Peter van Kekem


2 Answers

What about using System.ComponentModel.TypeConverter. It has methods to check whether it CanConvertFrom(Type) and CanConvertTo(Type) and has the "universal" ConvertTo Method which accepts an Object in and gives an Object back:

public Object ConvertTo(
    Object value,
    Type destinationType
)

Have a look here: http://msdn.microsoft.com/en-us/library/system.componentmodel.typeconverter.aspx

like image 174
Bazzz Avatar answered Oct 01 '26 15:10

Bazzz


Maybe you want to try this instead:

//For string...
string s = (o == null ? null : o.ToString());
//For int...
int i = (o == null ? 0 : Convert.ToInt32(o));

Maybe you can just put an if statement before so the code would read:

TheType s = null;

if (o is TheType)
    s = (TheType)o

This will only work with non-value-types. See this post for information on how to accomplish the "is" operator.

like image 43
Josh M. Avatar answered Oct 01 '26 13:10

Josh M.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!