1

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.

Community
  • 1
  • 1
TheGeekZn
  • 3,696
  • 10
  • 55
  • 91
  • 2
    Suggestion: Write a program and see how these perform. My guess is for all practical purposes it doesn't matter. It all comes down to style and what makes the most sense to you and other developers you work with. – drew_w May 05 '14 at 12:56
  • @drew_w for speed tests or benchmarking, writing an app will definitely do the trick. However, I have no idea how far down the CLR these are called, and would like to know if any method is clearly better than the other. – TheGeekZn May 05 '14 at 12:59
  • 1
    I'm confused. You seem to quote the answer to your question in your first paragraph. If your don't know if the object is a string or int then you clearly don't know your object is a string so you can't just cast. And I'm not sure what you mean by a `bit`. c# doesn't have one of them as far as I recall... – Chris May 05 '14 at 12:59
  • Sorry - I meant byte - I was actually thinking of SQL calls more than anything. – TheGeekZn May 05 '14 at 13:01

6 Answers6

3

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.

Flater
  • 12,908
  • 4
  • 39
  • 62
2

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;
}
middelpat
  • 2,555
  • 1
  • 20
  • 29
  • This answer heads in the direction of where my question was heading. – TheGeekZn May 05 '14 at 13:11
  • These are the "rules" which I use when deciding which technique I use for casting/converting. I also take in account wheter I want the code to throw an Exception or not (e.g. parse or tryparse) – middelpat May 05 '14 at 13:13
1

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.

Thom Smith
  • 13,916
  • 6
  • 45
  • 91
  • I always think like this: If you already know the value should be an integer, why isn't the type not an integer then? If the value is an text string entered by the user, I like to always protect myself from the user and use Parse or TryParse. – RvdK May 05 '14 at 13:04
  • You can come up with examples where you may reasonably rely on an value being an integer even if the type does not guarantee it. One common case is interfacing between components. Casts in C# should be uncommon, because the language's safe conversion operators and robust support for generics obviate common uses for casting. – Thom Smith May 05 '14 at 13:39
0
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");
0

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();

Max Yankov
  • 12,551
  • 12
  • 67
  • 135
0

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.

Elvedin Hamzagic
  • 825
  • 1
  • 9
  • 22