TheGeekZn
TheGeekZn

Reputation: 3924

Best way to cast/convert number to string

I was looking at the following question, comparing casting to converting, which basically stated (Through all the answers), that if you know your object is a string, use (string) rather than .ToString().

That got me thinking - what if your object might be a string or int? Or does knowing its a string also extend to integers?

Would this rule apply to a byte too? (Accidently used bit earlier)

Edit
This answer shows many ways of converting an integer to a string, but that still doesn't explain which to really use.

Upvotes: 1

Views: 19245

Answers (6)

Elvedin Hamzagic
Elvedin Hamzagic

Reputation: 855

My experience is that best cast/convert is archived through Convert class. That's the way C# expecting from you. That class care about all that ugly things that would you normally do. When you do type conversion or simply typecasting, it even round float to int.

Upvotes: 0

Max Yankov
Max Yankov

Reputation: 13327

I think that the best option, if you strongly suspect that it's a string, but not actually sure, is something like this:

string valueString = value is string ? (string) value : (value ?? string.Empty).ToString();

Upvotes: 0

Flater
Flater

Reputation: 13833

Specifically, casting a number to a string presents no real issue, as any number can be expressed as a string (Important: not every string, however, can be expressed as an number! e.g. how would you express "banana" as a number?)

string mystring = mynumber.ToString();

works everytime, without fail (assuming non-null values in case you're using nullable types).

The same exact method applies for any primitive type, and some others (DateTime, StringBuilder, ...)

It's the conversion from string to number that can be problematic. Usually not the other way around.

Edit if you want to take advantage of direct (string) casting in case your starting object is already a string, maybe this can help?

string mystring = (myobject as string) ?? myobject.ToString();

myobject as string will try to directly cast the object to a string. If it fails, that returns null.

?? myobject.ToString() then makes sure that, in case the previous attempts resulted in null, the regular .ToString() method is called as a fallback scenario.

Upvotes: 5

middelpat
middelpat

Reputation: 2585

If you have an object which is of type int but is boxed as an object, you cast it back:

object myBoxedStr = "stringvalue";
string unboxedStr = (string)myBoxedStr;

http://msdn.microsoft.com/en-us/library/yz2be5wk.aspx

If you have a string which contains an int value, you parse (or tryparse) it

string myIntStr = "5";
int myInt = int.Parse(myIntStr);

If you don't know if the boxed type is the assummed type you use is and as

object assumedMyType = new MyType();
MyType myType = assumedMyType as MyType;

the as keyword returns null if the conversion has failed (rather than throwing an exception)

With the is keyword you can check if the assumed type is of the correct type before converting it

object assumedInt = 5;
if(assumedInt is int)
{
    int myInt = (int)assumedInt;
}

Upvotes: 2

Ümit Polat
Ümit Polat

Reputation: 34

string name = GetSql["username"].ToString();

This code running slow. Because object(object, int, double etc.) to string converting operations.

string name = (string)GetSql["username"];

This code very fast running. Because not converting operations only type designation.

int to string convert.

1-)

var number = 0;
int.TryParse("213", out number);

It is better to TryParse method because it can block error occurs.

2-)

var number = int.Parse("123");

Upvotes: 0

Thom Smith
Thom Smith

Reputation: 14086

The takeaway from that question is that if you know that your value is actually of the type you want, then you should cast it (e.g. (int)). This has several benefits: it is efficient, it clearly expresses your intent, and it will fail conspicuously if your presumption is false.

You use other sorts of conversions when you don't know that the value of the type you want, or when you know that it is not. For instance, if you have an array of strings, you should not use (int), but rather ParseInt and its ilk. If you have an array of objects, some of which are ints, then the as operator might be what you want.

Upvotes: 1

Related Questions