Is it possible to achieve the following code? I know it doesn't work, but I'm wondering if there is a workaround?
Type k = typeof(double);
List<k> lst = new List<k>();
Yes, there is:
var genericListType = typeof(List<>);
var specificListType = genericListType.MakeGenericType(typeof(double));
var list = Activator.CreateInstance(specificListType);
A cleaner way might be to use a generic method. Do something like this:
static void AddType<T>()
where T : DataObject
{
Indexes.Add(typeof(T), new Dictionary<int, T>());
}
Related
Is it possible to achieve the following code? I know it doesn't work, but I'm wondering if there is a workaround?
Type k = typeof(double);
List<k> lst = new List<k>();
Yes, there is:
var genericListType = typeof(List<>);
var specificListType = genericListType.MakeGenericType(typeof(double));
var list = Activator.CreateInstance(specificListType);
A cleaner way might be to use a generic method. Do something like this:
static void AddType<T>()
where T : DataObject
{
Indexes.Add(typeof(T), new Dictionary<int, T>());
}
Right now, I'm doing this
var data = new JobDataMap(new Dictionary<string,string> { {"obj", "stringify"} });
But I want to do this:
dynamic d = new { obj = "stringify" };
var data = new JobDataMap(d);
Is there some secret syntactical sugar that would allow me to do this?
There's no magical way of doing this. There's no way the compiler can know that your Dynamic object really is a Dictionary at compile time.
That being said, you could create an extension method that converts it to a Dictionary so that you could do something like this:
dynamic d = new { obj = "stringify" };
var data = new JobDataMap(d.ToDictionary());
This blogpost offers an example: http://blog.andreloker.de/post/2008/05/03/Anonymous-type-to-dictionary-using-DynamicMethod.aspx
I have typeof(List<T>) as a Type object, but I need the typeof(List<>) from which I can use MakeGenericType() to retrieve a type object for List, is it possible?
Update: Guys, thx. This seems a trivial question. But anyway, I upvoted everyone and accepted the first answer.
If I undestand your problem correctly, you have a generic type (List<int>) and another type (lets say long) and you want to make a List<long>. That can be done like this:
Type startType = listInt.GetType(); // List<int>
Type genericType = startType.GetGenericTypeDefinition() //List<T>
Type targetType = genericType.MakeGenericType(secondType) // List<long>
However, if the types you are working with are indeed lists, it might be clearer if you actually used:
Type targetType = typeof(List<>).MakeGenericType(secondType) // List<long>
You can use Type.GetGenericTypeDefinition.
I assume you mean to achieve something like the below?
var list = new List<int>();
Type intListType = list.GetType();
Type genericListType = intListType.GetGenericTypeDefinition();
Type objectListType = genericListType.MakeGenericType(typeof(object));
The answer is Type.GetGenericTypeDefinition:
http://msdn.microsoft.com/en-us/library/system.type.getgenerictypedefinition.aspx
Example:
var t = typeof(List<string>);
var t2 = t.GetGenericTypeDefinition();
And then could do this:
var t = typeof(List<>);
var t2 = t.MakeGenericType(typeof(string));
Basic c# question. In the sample bellow But the 'is' doesn't like the type variable. Any ideas there should be a simple answer.
List<object> list = new List<object>();
list.Add("one");
list.Add(2);
list.Add('3');
Type desiredType = typeof(System.Int32);
if (list.Any(w => w is desiredType))
{
//do something
}
Try this:
List<object> list = new List<object>();
list.Add("one");
list.Add(2);
list.Add('3');
Type desiredType = typeof(System.Int32);
if (list.Any(w => w.GetType().IsAssignableFrom(desiredType)))
{
//do something
}
Anyway: are you sure you want to create a list of objects?
w.GetType() == desiredType.
Why are you abusing generics like that?
You could use the Linq extension method OfType:
list.OfType<> will return an IEnumerable to any items of the specified type.
If I recall correctly you have to write w is System.Int32..
The delegate is expecting a type or a namespace, but you're supplying a type instance. Try this:
if (list.Any(w => w is Int32))
{
//do something
}
I know this does not work, however does anyone have a way of making it work?
object obj = new object();
MyType typObj = new MyType();
obj = typObj;
Type objType = typObj.GetType();
List<objType> list = new List<objType>();
list.add((objType) obj);
EDIT:
Here is the current code: http://github.com/vimae/Nisme/blob/4aa18943214a7fd4ec6585384d167b10f0f81029/Lala.API/XmlParser.cs
The method I'm attempting to streamline is SingleNodeCollection
As you can see, it currently uses so hacked together reflection methods.
It seems you're missing an obvious solution:
object obj = new object();
MyType typObj = new MyType();
obj = typObj;
List<MyType> list = new List<MyType>();
list.Add((MyType) obj);
If you really need the dynamic route, then you could do something like this:
object obj = new object();
MyType typObj = new MyType();
obj = typObj;
Type objType = typObj.GetType();
Type listType = typeof(List<>);
Type creatableList = listType.MakeGenericType(objType);
object list = Activator.CreateInstance(creatableList);
MethodInfo mi = creatableList.GetMethod("Add");
mi.Invoke(list, new object[] {obj});
You need reflection:
constructor = typeof (MyType).GetConstructor () // doing this from memory, the typeof might be wrong, I'm sure someone will edit it
typObj = (MyType) constructor.Invoke ()
It can also be done for generics but that is a bit trickier.
You can do something like this using Generics, I'm not really sure what the point of it would be though.
public List<T> TypedList<T>() where T : new()
{
object obj = new object();
T typObj = new T();
obj = typObj;
List<T> list = new List<T>();
list.Add((T)obj);
return list;
}
object obj = new object();
Type objType = obj.GetType();
IList list = (IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(objType));
list.Add(obj);
With this you will get an runtime error if you try to put something into list that is not assignable from objType.
Even though it seems answered, I still don't get it :)
Wouldn't it be useful to have the "typeToReturn" as generic argument to the function?
public List<T> SingleNodeCollection<T>(String xPath, XPathNavigator navigator)
where T : new()
{
XPathNodeIterator nodes = navigator.Select(xPath);
List<T> returnedList = new List<T>(nodes.Count);
...
T newObj = new T();
...
Type t = typeof(T); // need the type anyway?
}
public class myClass
{
}
myClass instance = new myClass();
Type t = instance.GetType;
//top is just to show obtaining a type...
public object GetListOfType(Type t)
{
Type listType = typeof(List<>);
var listOfType = listType.MakeGenericType(t);
var listOfMyClassInstance = Activator.CreateInstance(listOfType);
return listOfMyClassInstance;
}
but eventually you have to cast... using your type directly
List<object> listOfMyClass = GetListOfType(t);
listOfMyClass.Add(myClassInstance);
((myClass)listOfMyClass[0]).SomeProperty
Faster would be to use Reflection.Emit
Here's a simple example of using Reflection.Emit for instantiating an arbitrary concrete type at runtime. For your purposes, you just need to have it call the ctor of List instead of T.ctor as in the example.
I'm not entirely sure what you are trying to do, but would this work:
var obj = new MyType();
I might be misunderstanding your question though.
(I edited this to fix sample code which wouldn't compile, thanks for the comment)