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);
Related
How can I access the objects property in this situation?
Araba araba = new Araba();
araba.Renk = "mavi";
araba.fiyat = 12345;
// I created this class and it working normally
ArrayTypedStack asd = new ArrayTypedStack(10);
asd.Push(araba);
object araba2 = asd.Pop();
araba2. //cant access
Here you are assigning the value of asd.Pop() to a variable of the type object.
object is the root of all objects (all objects inherit from it and can be casted to it) and as such has no real information about what it is. It's just like any object in real life is a thing.
The solution here is to declare the araba2 as the type Araba, that will give you access to all the properties on the next line.
I don't know the implementation of the ArrayTypedStack and what the Pop() method looks like (it's return type) so it's possible that this will give you an error, saying that it can't convert an object to the type Araba. This is the type safety implemented in .NET. You have to convince .NET that it's of the type Araba, this can be by casting
Araba araba2 = (Araba)asd.Pop();
this can still give an error on runtime if the object returned from Pop() isn't of the type Araba, in this case you can ask .NET to try to cast it, there are serveral options for this:
object popResult = asd.Pop();
if (popResult is Araba) {
Araba araba2 = (Araba)popResult;
}
// can be written as follows:
if (popResult is Araba araba3) {
araba3.fiyat = 65432;
}
// can also be done as follows
Araba araba4 = asd.Pop() as Araba;
if (araba4 != null) {
araba4.fiyat = 84368;
}
Well, your araba2 variable is of type object. Thus, regardless of the actual type of the instance it contains, through the object variable araba2 you can only access members that are provided by the type object.
To access members provided by the Araba type (and assuming the instance in the araba2 variable is an instance of type Araba), the araba2 variable itself should be of type Araba, or the value of araba2 needs to be cast as Araba.
Thus,
var araba2 = asd.Pop();
or
var araba2 = (Araba) asd.Pop();
with the first example code line above requiring that the return type of the Pop method is Araba (or a type derived from Araba). The latter code line example will work regardless of the return type of Pop as long as the value returned by Pop is an actual Araba instance (or is something that is convertible to an Araba instance).
The following doesn't work, of course. Is there a possible way, which is pretty similar like this?
Type newObjectType = typeof(MyClass);
var newObject = givenObject as newObjectType;
newObjectType is an instance of the Type class (containing metadata about the type) not the type itself.
This should work
var newObject = givenObject as MyClass;
OR
var newObject = (MyClass) givenObject;
Casting to an instance of a type really does not make sense since compile time has to know what the variable type should be while instance of a type is a runtime concept.
The only way var can work is that the type of the variable is known at compile-time.
UPDATE
Casting generally is a compile-time concept, i.e. you have to know the type at compile-time.
Type Conversion is a runtime concept.
UPDATE 2
If you need to make a call using a variable of the type and you do not know the type at compile time, you can use reflection: use Invoke method of the MethodInfo on the type instance.
object myString = "Ali";
Type type = myString.GetType();
MethodInfo methodInfo = type.GetMethods().Where(m=>m.Name == "ToUpper").First();
object invoked = methodInfo.Invoke(myString, null);
Console.WriteLine(invoked);
Console.ReadLine();
You can check if the type is present with IsAssignableFrom
if(givenObject.GetType().IsAssignableFrom(newObjectType))
But you can't use var here because type isn't known at compile time.
I recently had the case, that I needed to generate some code like in Tomislav's answer. Unfortunately during generation time the type T was unknown. However, a variable containing an instance of that type was known. A solution dirty hack/ workaround for that problem would be:
public void CastToMyType<T>(T hackToInferNeededType, object givenObject) where T : class
{
var newObject = givenObject as T;
}
Then this can be called by CastToMyType(instanceOfNeededType, givenObject) and let the compiler infer T.
You can use Convert.ChangeType. According to msdn, it
returns an object of a specified type whose value is equivalent to a
specified object.
You could try the code below:
Type newObjectType = typeof(MyClass);
var newObject = Convert.ChangeType(givenObject, newObjectType);
Maybe you can solve this using generics.
public void CastToMyType<T>(object givenObject) where T : class
{
var newObject = givenObject as T;
}
I have a 'basetype' object that I wish to cast to a specific type. I want to make this generic, so I wish to get the name of the object and cast it to a class with the same name. Something like so :
string name = baseObj.name;
var baseObj = baseObj as getClassFor(name);
I have found the Activator but I Activator.CreateInstance(), i dont think, is what I need.
My question is, how do I cast an object to a certain type based on a string?
As casting is mostly a compile time thing, you can't cast to a specific Type based on a string, so you have to use the dynamic keyword.
var t= Type.GetType(baseObj.name); //This should contain the correct namespace too. ex. "MyNamespace.SpecificClass"
dynamic specificObj = Convert.ChangeType(baseObj, t);
specificObj.SpecificMethod();
I am trying to get a type from a Type variable. For example:
Type t = typeof(String);
var result = SomeGenericMethod<t>();
An error happens on the second line, because t is not a type, it's a variable. Any way to make it a type?
To make an instance of a generic based on a Type, you can use reflection to get an instance of the generic with the type you want to use, then use Activator to create that instance:
Type t = typeof (string); //the type within our generic
//the type of the generic, without type arguments
Type listType = typeof (List<>);
//the type of the generic with the type arguments added
Type generictype = listType.MakeGenericType(t);
//creates an instance of the generic with the type arguments.
var x = Activator.CreateInstance(generictype);
Note that x here will be an object. To call functions on it, such as .Sort(), you'd have to make it a dynamic.
Please Note that this code is hard to read, write, maintain, reason about, understand, or love. If you have any alternatives to needing to use this sort of structure, explore those thoroughly.
Edit: You can also cast the object you receive from the Activator, such as (IList)Activator.CreateInstance(genericType). This will give you some functionality without having to resort to dynamics.
No, you cannot know the value of a Type object at compile time, which is what you would need to do in order to use a Type object as an actual type. Whatever you're doing that needs to use that Type will need to do so dynamically, and not require having a type known at compile time.
An ugly workaround using reflection:
Class with generic Method
public class Dummy {
public string WhatEver<T>() {
return "Hello";
}
}
Usage
var d = new Dummy();
Type t = typeof(string);
var result = typeof(Dummy).GetMethod("WhatEver").MakeGenericMethod(t).Invoke(d, null);
On class instantiation see Max's solution
I want to create an instance of type t with reflection, that is
Type t = typeof(string);
string s = (t)Activator.CreateInstance(t); // this fails because of convertion
string s = Activator.CreateInstance(t) as t // also fails
Is there a way to perform such a convertion?
Thanks.
Yes. You have to convert to string, not to t. You may want a generic method, alternatively:
public T GetInstance<T>()
{
Type t = typeof(T);
T s = (T)Activator.CreateIstance(t);
return s;
}
As things stand you are attempting to cast an object that is actually an instance of System.String to type System.Type...
Try this:
string s = (string)Activator.CreateInstance(t);
Activator.CreateInstance returns an instance boxed in an object so it must be cast to the correct type before you can use it.
In your example t is a Type object variable and not a type reference. You must either specify the type directly as in my example or you can use generics.