Dynamic casting based on a string - c#

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.

Related

Remove property and it's value from dynamic object in C#

In PHP we can remove one property and its value from the object simply with this code:
$foo->bar = "Something";
unset($foo->bar);
I want to do this in C#.
Imagine that the object is:
var a = new {foo = bar, one = "one"}
How I can remove foo from the object?
Types are defined at compile-time, so there's no removing of properties, not in c#. An anonymous type is a type just like classes that you create; it's just that the name is hidden from you.
The closest you can get to your answer is to define a new type that omits the property you wish to remove:
var b = new { one = a.one };

how get values from object to local variable 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.

Type variable to generic type

Sorry my bad english.
My code in C#.
I have variable:
Type t = /* Variable with any unknown type */
And i need in used template:
var b = GetData</* I need used variable t in here */>();
How do it?
OR
I need variable
object c = /*any data*/
Type type = /*any type*/
I need this:
var b = (type)c;
How do it?
In this case if c could actually be a different type but is convertible then you can use something like this.
For example "123" is a string but convertible to an integer.
object c = "123";
Type type = typeof(int);
var b = Convert.ChangeType(c, type);

How to use the type 'Type'

I know that I can use the type string as:
string someString = "This is my string";
I am not sure how to use the type Type
Type someType = someString.GetType();
How could I create a variable based on that type. I want to do something like
someType someOtherString = "here is another string";
//string
In other words, how could I create a variable based on some type?
There are a few ways to go about this, but the simplest would be to use the Activator class.
http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx
Example:
Type t = someClassInstance.GetType();
object o = Activator.CreateInstance(t);
Variable types have to be known at declaration time. You can declare a variable of type object and then dynamically create an instance of a type which you only know about at execution time, but you can't dynamically declare a variable like that.
The closest you could get would be to create a generic type and instantiate that using a type argument specified with reflection. Then you really would have a variable of the right type - but you wouldn't be able to do anything particularly useful with it.
It's important to distinguish between the type of a variable and the type of the object a variable's value may refer to. For example:
object foo = Activator.CreateInstance(someType);
will end up with a variable of type object, but the value of foo will be a reference to an instance of whatever type someType refers to.
Try
var object = Activator.CreateInstance(myType);
Starting from C# 3 you can do:
var someOtherString = "here is another string";
This way you don't care what's the type, var is type "joker" and save you the need to know the type at declaration time.
Hope that's what you mean?
use Assembly.CreateInstance()
Type type = typeof(String);
Assembly asm = Assembly.GetExecutingAssembly();
object blah = asm.CreateInstance(type.FullName);

.NET generic class instance - passing a variable data type

As the title suggests, I'm tyring to pass a variable data type to a template class. Something like this:
frmExample = New LookupForm(Of Models.MyClass) 'Works fine
Dim SelectedType As Type = InstanceOfMyClass.GetType() 'Works fine
frmExample = New LookupForm(Of SelectedType) 'Ba-bow!
frmExample = New LookupForm(Of InstanceOfMyClass.GetType()) 'Ba-bow!
LookupForm<Models.MyClass> frmExample;
Type SelectedType = InstanceOfMyClass.GetType();
frmExample = new LookupForm<SelectedType.GetType()>(); //Ba-bow
frmExample = new LookupForm<(Type)SelectedType>(); //Ba-bow
I'm assuming it's something to do with the template being processed at compile time but even if I'm off the mark there, it wouldn't solve my problem anyway. I can't find any relevant information on using Reflection to instance template classes either.
(How) can I create an instance of a dynamically typed repository at runtime?
A C# example of something pretty close is located here on a question I had:
typeof(MyClass).GetMethod("Foo").MakeGenericMethod(new[] { param.GetType() }).Invoke(null, new[] { param });
Converting to VB.NET, changing it to type creation not method invocation and using your example names for you:
Dim frmExample as LookupForm<Models.MyClass>;
Dim SelectedType as Type = InstanceOfMyClass.GetType();
Dim GenericLookupType as Type = GetType(LookupForm(Of)).MakeGenericType(SelectedType)
frmExample = Activator.CreateInstance(GenericLookupType, new object(){})
(Ah for some reason I thought you wanted it in VB.NET but here is a C# example)
LookupForm<Models.MyClass> frmExample;
Type SelectedType = InstanceOfMyClass.GetType();
Type GenericLookupType = typeof(LookupForm<>).MakeGenericType(SelectedType);
frmExample = Activator.CreateInstance(GenericLookupType, new object[]{});
Use Type.MakeGenericType.
Type modelType = typeof(Models.MyClass);
var repoType = typeof(LookupForm<>).MakeGenericType(new [] {modelType} );
//at this point repoType == typeof(LookupForm<Models.MyClass>);
var repo = Activator.CreateInstance(repoType );
//Ta-dah!!!
And VB.NET version :)
Dim modelType As Type = GetType(Models.MyClass)
Dim repoType As Type = GetType(LookupForm(Of )).MakeGenericType(New Type() {modelType})
'at this point repoType = GetType(LookupForm(of Models.MyClass))'
Dim repo = Activator.CreateInstance(repoType)
'Ta-dah!!!'
This sounds like a candidate for the Dynamic Language Runtime, 'Dynamic' type in C#, but that would require you to use .NET 4.0
Unfortunately you can't do this without reflection and even then its not very friendly. The reflection code will looks something like this:
Type baseType = typeof(LookupForm<>);
Type selectedType = InstanceOfMyClass.GetType(); //or however else you want to get hold of it
Type genericType = baseType.MakeGenericType(new Type[] { selectedType });
object o = Activator.CreateInstance(genericType);
Of course now you don't know what to cast your object to (assuming selectedType was dynamically set), but you can still call the methods on it via reflection, or you could create a non-generic interface to cast it to & call the methods on that.

Categories