I have a simple cast issue in following simple c# method
using System;
using System.Data.SqlTypes;
...
private void method1() {
string s = "TestString";
object o = s;
SqlString t1 = (SqlString) s;
SqlString t2 = (SqlString) o;
}
...
When casting directly from s (in case of t1), I don't get any error but when casting from o I get exception:
Specified cast is not valid.
I have same problem converting from object to all types System.Data.SqlTypes
How can I cast an object that has string in it to SqlString?
This is because there is an implicit conversion operator for String to SqlString.
In other words, you are not dealing with a simple built-in cast: designers of SqlString decided to allow you cast strings to SqlString. They didn't do it for Object, hence the error that you are seeing.
To answer your question
private void method1() {
object o = "MyString";
SqlString t1 = o as String
}
if o is not a string, t1 will be null.
Neither of the other answers addresses the question of casting the object reference to the SqlString. If you are certain that the object reference points to a string, it's simple:
var ss = (SqlString)(string)o;
If o might hold a value other than a string, you can do this, instead:
var ss = (SqlString)(o as string);
Or, if you want to go down the (dangerous) path of storing non-string data in string format:
var ss = o == null ? (SqlString)null : o.ToString();
Well, you could do this: var x = new SqlString("hi mom")
Or, as in the example you provided:
string s = "TestString";
object o = s;
SqlString t1 = new SqlString((string)o);
A word of general advice: Your life will probably be much easier if you learn to use Intellisense and MSDN documentation prior to posting on StackOverflow. You could've answered this question yourself in about 5 seconds by using documentation.
Related
I have been trying to set some field values of specific objects in C#.
For other reasons I need to construct a List of values from a string then I want to assign this to a field in an object.
The way I indicate the value type of the list is something like this in string
name:type{listItemName:listItemType{listItemValue}}
This list can be of any type, so it is undetermined until we reach conversion.
I am using
List<dynamic> ldy = new List<dynamic>();
foreach (string listElement in listElements)
{
if (listElement == "") continue;
Type leDataType = GetDataType(listElement);
string leData = GetDataRaw(listElement);
var leDynamic = ConstructDataObject(leDataType, leData, listElement);
ldy.Add(leDynamic);
}
Which ends up with the correct data and with the correct data type when I enquire, however when I am trying to use the resulting ldy list and assign it to a field, of course it acts as a List<object>
thus not allowing me to assign.
Finally so, I am using field.SetValue(targetObject, ldy); to assign the value to the field.
The error message I am getting is
ArgumentException: Object of type 'System.Collections.Generic.List`1[System.Object]' cannot be converted to type 'System.Collections.Generic.List`1[System.Int32]'.
Which to be clear, I do understand and I do understand why, however I dont really see how could I solve this issue, not by solving this nor by changing the fundaments of my code design.
Please help!
As #juharr suggested I have searched for solutions to do this with reflection.
Here is my solution:
private static IList GetTypedList(Type t)
{
var listType = typeof(List<>);
var constructedListType = listType.MakeGenericType(t);
var instance = Activator.CreateInstance(constructedListType);
return (IList)instance;
}
I have this JToken
var pv = JToken.Parse(keys["parameterValues"].ToString()).ToList()[0];
Which returns this value
{"DE:Actual Savings": 42217.0}
I can't use .Value because the float is represented as an object {42217.0}
How can I get this number? Right now I am using .ToString() and converting it
To convert the value to a defined type you could use one of the defined methods below:
System.Convert.ChangeType(jtoken.ToString(), targetType);
or
JsonConvert.DeserializeObject(jtoken.ToString(), targetType);
Let's take into consideration our sample:
string json = #{"DE:Actual Savings": 42217.0}
You could do something like:
var obj = (JObject)JsonConvert.DeserializeObject(json);
Type type = typeof(float);
var i1 = System.Convert.ChangeType(obj["DE:Actual Savings"].ToString(), type);
Hope this solves your problem.
i have following code please help me how to get values from object
APIKarho objapi = new APIKarho();
object obje = objapi.GetBookingFromAPI();
string ss = obje.booking_id;
You should cast the object to the class it originally is (what class is the object returned by GetBookingFromAPI()) before you could access its field/property/method. Example:
public MyClass { // suppose this is the original class of the object returned by GetBookingFromAPI
public int booking_id;
}
APIKarho objapi = new APIKarho();
object obje = objapi.GetBookingFromAPI();
string ss = ((MyClass)obje).booking_id; //note the casting to MyClass here
You need to find out what type GetBookingFromAPI() returns, and change the type of obje. Just move your mouse over GetBookingFromAPI().
GetBookingFromAPIType obje = objapi.GetBookingFromAPI();
string ss = obje.booking_id;
If your api returns an object of an unknown type or a type that you cannot cast to you could use the dynamic keyword.
dynamic obj = api.GetBookingFromAPI();
string ss = obj.booking_id;
Note that this works only if booking_id is actually a string.
I'm using JSON.NET to deserialize a JSON file to a dynamic object in C#.
Inside a method, I would like to pass in a string and refer to that specified attribute in the dynamic object.
For example:
public void Update(string Key, string Value)
{
File.Key = Value;
}
Where File is the dynamic object, and Key is the string that gets passed in. Say I'd like to pass in the key "foo" and a value of "bar", I would do:
Update("foo", "bar");, however due to the nature of the dynamic object type, this results in
{
"Key":"bar"
}
As opposed to:
{
"foo":"bar"
}
Is it possible to do what I'm asking here with the dynamic object?
I suspect you could use:
public void Update(string key, string Value)
{
File[key] = Value;
}
That depends on how the dynamic object implements indexing, but if this is a Json.NET JObject or similar, I'd expect that to work. It's important to understand that it's not guaranteed to work for general dynamic expressions though.
If you only ever actually need this sort of operation (at least within the class) you might consider using JObject as the field type, and then just exposing it as dynamic when you need to.
Okay so it turns out I'm special. Here's the answer for those that may stumble across this in future,
Turns out you can just use the key like an array index and it works perfectly. So:
File[Key] = Value; Works the way I need as opposed to
File.Key = Value;
Thanks anyway!
You can do it, if you're using JObject from JSON.NET. It does not work with an ExpandoObject.
Example:
void Main()
{
var j = new Newtonsoft.Json.Linq.JObject();
var key = "myKey";
var value = "Hello World!";
j[key] = value;
Console.WriteLine(j["myKey"]);
}
This simple example prints "Hello World!" as expected. Hence
var File = new Newtonsoft.Json.Linq.JObject();
public void Update(string key, string Value)
{
File[key] = Value;
}
does what you expect. If you would declare File in the example above as
dynamic File = new ExpandoObject();
you would get a runtime error:
CS0021 Cannot apply indexing with [] to an expression of type 'ExpandoObject'
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!
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
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.
The problem is, the 'as' operator cannot be used with a non reference type.
For example:
public class ConverterThingy
{
public T Convert<T>(object o)
where T : class
{
return o as T;
}
public T Convert<T>(object o, T destinationObj)
where T : class
{
return o as T;
}
}
This should work for most of it. You can do the as conversion from any object to another reference type.
SomeClass x = new ConverterThingy().Convert<SomeClass>(new ExpandoObject());
// x is null
SomeClass x = null;
x = new ConverterThingy().Convert(new ExpandoObject(), x);
// x is null, the type of x is inferred from the parameter