Convert or Cast Object to String

Casting vs Converting an object toString, when object really is a string

The two are intended for different
purposes. The ToString method of any
object is supposed to return a string
representation of that object. Casting
is quite different, and the 'as' key
word performs a conditional cast, as
has been said. The 'as' key word
basically says "get me a reference of
this type to that object if that
object is this type" while ToString
says "get me a string representation
of that object". The result may be the
same in some cases but the two should
never be considered interchangeable
because, as I said, they exist for
different purposes. If your intention
is to cast then you should always use
a cast, NOT ToString.

from http://www.codeguru.com/forum/showthread.php?t=443873

see also http://bytes.com/groups/net-c/225365-tostring-string-cast

Convert or cast object to string

You can't cast any random value to a string. A force cast (as!) will fail if the object can't be cast to a string.

If you know it will always contain an NSNumber then you need to add code that converts the NSNumber to a string. This code should work:

if let result_number = single_result.valueForKey("Level") as? NSNumber
{
let result_string = "\(result_number)"
}

If the object returned for the "Level" key can be different object types then you'll need to write more flexible code to deal with those other possible types.

Swift arrays and dictionaries are normally typed, which makes this kind of thing cleaner.

I'd say that @AirSpeedVelocity's answer (European or African?) is the best. Use the built-in toString function. It sounds like it works on ANY Swift type.

EDIT:

In Swift 3, the answer appears to have changed. Now, you want to use the String initializer

init(describing:)

Or, to use the code from the question:

result = single_result.valueForKey("Level")
let resultString = String(describing: result)

Note that usually you don't want valueForKey. That is a KVO method that will only work on NSObjects. Assuming single_result is a Dictionary, you probably want this syntax instead:

result = single_result["Level"]

casting object to string[]

You can explicitly cast your object to string[] or use as operator like:

string[] returnValue = fixOutput(data) as string[];

Or

string[] returnValue = string[](fixOutput(data));

But more importantly , why are you returning a string array inside an object ?. You can modify your method to return a string array or IEnumerable<string>

C# cast object to another type stored in string variable

You can use Activator.CreateInstance to create an instance of a type. See https://msdn.microsoft.com/en-us/library/wccyzw83(v=vs.110).aspx

var myword = Activator.CreateInstance(wordType);

And then you can set the properties on it using reflection, or by casting it to the base class MyWord.

OR you could use reflection on the wordType to find its constructor and call that.

BUT really, are there that many word types that it's not easier (and a whole lot faster) to maintain a Dictionary<string,Func<string, string, WordType>> where you can look up a word type and get a function that makes one for you from its word and definition values?

wordFactories["noun"](word, definition);

Another alternative is to use Impromptu.Interface from Nuget which can wrap any dynamic object in an interface and have it behave just like that. In my natural language engine for .NET that's what I use to take a word from a database and then wrap it up as, say, an INoun, an IPluralNoun, an IMammal, etc.

C# Options to explicitly cast an object as a string

There are many good responses to this here: Direct casting vs 'as' operator?

In short, the first option i.e. (string)Session["test"] == "abc" will throw a InvalidCastException if Session["test"] is not a string. Use this if you might want to throw an error on invalid cast.

The second option Session["test"] as string == "abc" will return null if the object which is typecasted is not a string. This option requires an explicit null check to be done post conversion before actually using the result.

If you definitely know that the object which you are typecasting is a string, you can use the first one and if in case it fails, you will definitely know that the cast failed and is easier to debug. If you are not sure of whether the object is a string, you might want to go for the second option.

Converting an object to string with a specified culture

You only have to cast it to the IConvertible interface:

object o = ...;
string s = ((IConvertible)o).ToString(cultureInfo);

Convert Object to String in java

As you've noticed you get the string "null" instead of an actual null value. This is by design:

Returns:
if the argument is null, then a string equal to "null"; otherwise, the value of obj.toString() is returned.

That said, you could just check if it's null before converting it:

import java.math.BigDecimal;

class Main
{
public static void main (String[] args)
{
BigDecimal foo = new BigDecimal(1.0);
BigDecimal bar = null;

// if the value isn't NULL, use String.valueOf, else use NULL
String fooString = foo != null ? String.valueOf(foo) : null;
String barString = bar != null ? String.valueOf(bar) : null;

System.out.println(fooString == null ? "REALNULL" : "\"" + fooString + "\"");
System.out.println(barString == null ? "REALNULL" : "\"" + barString + "\"");
}
}

Output:

"1"
REALNULL

DEMO



Related Topics



Leave a reply



Submit