C# Best Practices

For casting objects, what’s the best practice?

string pNum = (string)ttQuoteDtlR["PartNum"];
int qNum = (int)ttQuoteDtlR["QuoteNum"];


string pNum = ttQuoteDtlR["PartNum"].ToString();
int qNum = Convert.ToInt32(ttQuoteDtlR["QuoteNum"]);

What about using ttQuoteDtlR[“PartNum”] vs ttQuoteDtlR.PartNum?

Any of those are fine. Personally I like the direct cast (int) because I’m lazy. If you need some special handling, a good thing to use is TryParse which will catch any failures

int myIntResult = 0;
bool GoodConversion = int.TryParse(aString, out myIntResult);
//now you can test for a good conversion, then use the myIntResult

[quote="willetta, post:1, topic:44187"]
What about using ttQuoteDtlR[“PartNum”] vs ttQuoteDtlR.PartNum?
Always use the strongly typed version, ttQuoteDtlR.PartNum. This allows the compiler to do some error checking for you.
1 Like

If you know the data type, the above methods are just fine. If you don’t know the data type, you would want a tryparse like @Chris_Conn showed. You could also let the compiler decide by using a var keyword instead of an explicit data type.


Convert.ToXX is a little nicer than straight cast IMO
Straight Casting (int) requires that the field already be an integer or a numeric type (decimal, double) it also truncates the decimal if casting from a double / decimal

Convert.ToInt32() does a lot more than straight casting, it can convert to an int ANY primitive and it also does Rounding instead of truncating.



FYI, in BPMs you can also use the following for your UD Fields.

row.SetUDField<System.String>("Column", "Hello World!");


var partPlants = from    tpp in ttPartPlant
where   tpp.Updated() && tpp.UDField<System.Decimal>("Number01") == 0
select  tpp;