Reputation: 781
I need to pass a Type as data using a DataObject instance. I tried the following code but the result is null.
DataObject data = new DataObject(typeof(String));
Type result = (Type)data.GetData(typeof(Type)); //expected result to be typeof(String)
I am trying to do something like the following, but I am working with Type objects rather than String ones.
DataObject data = new DataObject("abc");
String result = (String)data.GetData(typeof(String)); //the result is "abc"
Any idea why I cannot pass Type objects using DataObject?
--- EDIT1 ---
I am actually using System.Windows.DataObject
to figure out why DragEventArgs.Data.GetData
method returns null
. DragEventArgs.Data
is an IDataObject
and I use DataObject
to simplify my test code.
Upvotes: 0
Views: 2232
Reputation: 781
I've found a way to make it working. It also works with DragEventArgs.Data
.
DataObject data = new DataObject(typeof(String));
Type result = (Type)data.GetData(typeof(Type).GetType());
It seems that typeof()
returns objects of type Type
rather than RuntimeType
. The only way to get the RuntimeType
is to call typeof(ANY_CLASS).GetType()
. I used the following code sample to figure this out.
string str1 = new Object().GetType().ToString(); //System.Object
string str2 = typeof(Object).ToString(); //System.Object
string str3 = typeof(Object).GetType().ToString(); //System.RuntimeType
string str4 = typeof(Type).ToString(); //System.Type
string str5 = typeof(Type).GetType().ToString(); //System.RuntimeType
Upvotes: 0
Reputation: 82474
I think you are looking for generics:
public class DataObject<T>
{
private T _data;
public DataObject(T data)
{
_data = data;
}
public T GetData()
{
return _data;
}
}
Then you can do this:
var data = new DataObject("abc");
string result = data.GetData();
Upvotes: 3