how get values from object to local variable c# - c#

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.

Related

How to use a variable to access an object member in c#

I have a web service that returns a custom object (a struct type) APIStruct user.
I have a variable holding the name of the current field it is checking for currentField.
Now, in a situation where user contains first_name and last_name, I can access the value using user.first_name or user.last_name. BUT, is it possible to hold the field name in a variable and access the value through the variable? working like:
var currentField = "first_name";
var value = user.currentField;
Obviously the above is not working, so is there any way to do this? In the past with languages such as PowerShell it works just like above $currentField = "first_name"; $value = user.$currentField
I've tried user.currentField user.(currentField) user[currentField] user.$currentField
You can extend your object class to support access to a Dictionary of additional properties, accessible through an explicit indexer.
public class myClass
{
private Dictionary<string, object> Something = new Dictionary<string, object>();
public object this[string i]
{
get { return Something[i]; }
set { Something[i] = value; }
}
}
Use like this:
myClass m = new myClass();
Set value:
m["fist name"] = "Name";
m["level"] = 2;
m["birthday"] = new DateTime(2015, 1, 1);
Get value:
int level = (int)m["level"];
string firstName = (string)m["first name"];
DateTime dt = (DateTime)m["birthday"];
you must use reflection. Create a method like this:
public static object GetPropValue(object src, string propName)
{
return src.GetType().GetProperty(propName).GetValue(src, null);
}
and call it:
string currentField = "first_name";
GetPropValue(user, currentField);
But it must be said, it is not the way you should use for the standard reading of object values.
What you're looking for called Reflection.
var type = user.GetType(); // Get type object
var property = type.GetProperty(currentField); // get property info object
var value = property.GetValue(user); // get value from object.
Be careful - reflection is pretty slow compared to direct property access.
Another option you may have is to use a switch statement. Something like:
switch (currentField){
case "first_name":
value = user.first_name;
break;
case "last_name":
value = user.last_name;
break;
etc...

can't understand how to call this function

I have a third party dll added to my web application.one of the function looks like this
public InterestCategory[] gvc(string st)
{
object[] results = this.Invoke("getit", new object[] {
st});
return ((InterestCategory[])(results[0]));
}
as you can see the function returns InterestCategory[].When I checked (GoToDefinition) InterestCategory I can see this
public partial class InterestCategory
{
private string descriptionField;
public string Description
{
get
{
return this.descriptionField;
}
set
{
this.descriptionField = value;
}
}
}
And now In my code I am trying to call this function like this
API.InterestCategory IC = new API.InterestCategory();
IC = api.gvc(st);
it throws an error like this
Cannot implicitly convert type 'API.InterestCategory[]' to 'API.InterestCategory'
Can any one tell me what is the correct procedure to call this function
You are specifying the wrong type for the variable. You have told the compiler you want to create a single variable of type InterestCategory when the function is returning an array, InterestCategory[].
Change your code to this and it should work fine:
API.InterestCategory[] ICs;
ICs = api.gvc(securityToken);
IC should be an array of Api.InterestCategory. Instead, you are declaring the variable as Api.InterestCategory. Try:
Api.InterestCategory[] IC = api.GetValidInterestsCategories(securityToken);
The method returns an array, so you must assign the result to a variable of the correct type:
InterestCategory[] ics = api.gvc(securityToken);
API.InterestCategory IC = new API.InterestCategory();
so typing
IC = api.gvc is mistake because IC is InterestCategory not InterestCategory[]
Try:
var IC = api.gvc(securityToken)
hello you are doing everything right but the problem you are getting due to mismatch of return type and variable in which you want to store it..i don't know why are you not able to Understand this problem..it belongs to the basics of programming..so do this.
api.InterestCategory[] ic = api.gvc(securityToken);

Exception When Casting String Object to SqlString

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.

C# CodeGeneration variable as type

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

Dynamic casting based on a string

Is there a way in C# to cast an object based on a string?
Example,
String typeToCast = control.GetType().Name;
Button b = (typeToCast)control;
Yes you can but you should not.
Csharp
string value = "2.5";
object typedObject;
typedObject = Convert.ChangeType(value, Type.GetType("System.Double"));
Vbnet
Dim value As String = "2.5"
Dim typedObject As Object
typedObject = Convert.ChangeType(value, Type.GetType("System.Double"))
No, you can't do that. Also, what would you achieve, as you have to assign it to "static" type, in your case, it's Button - So why not just cast it normally:
Button b = (Button)control;
You can hovewer, check if your control is of a type:
Type t = TypeFromString(name);
bool isInstanceOf = t.IsInstanceOfType(control);
Edit:
To create an object without having it type at compile time, you can use Activator class:
object obj = Activator.CreateInstance(TypeFromString(name));
Button button = (Button)obj; //Cast to compile-time known type.

Categories