Reputation: 23187
I'm trying to write a method that uses the following two arguments:
ColumnToSort
ColumnType
The reason I want to be able to do this is interpreting two things as a string can give a different result than comparing the same two things as a number. For example
String: "10" < "2"
Double: 10 > 2
So basically, I want to be able to send double or string datatype as a method argument, but I don't know how to do this, but it seems like something that should be possible in C#.
Addendum:
What I want my method to look like:
InsertRow(customDataObj data, int columnToSort, DataType dataType){
foreach(var row in listView){
var value1 = (dataType)listView.Items[i].SubItems[columnToSort];
var value2 = (dataType)data.Something;
//From here, it will find where the data object needs to be placed in the ListView and insert it
}
}
How it will be called:
I think the above provides enough of an explanation to understand how it will be called, if there are any specific questions, let me know.
Upvotes: 5
Views: 7914
Reputation: 6009
You might consider using generics.
InsertRow<T>(T data, int columnToSort){
foreach(var row in listView){
var value1 = (T)listView.Items[columnToSort].SubItems[columnToSort];
var value2 = data;
//From here, it will find where the data object needs to be placed in the ListView and insert it
if(typeof(T)==typeof(string))
{
//do with something wtih data
}
else if(typeof(T)==typeof(int))
{
//do something else
}
}
}
Then call it, and let it figure out the type by itself.
int i=1;
InsertRow(i,/*column/*);
You may also want to restrict what T can be, for instance if you want to make sure it's a value type, where T:struct
More
Upvotes: 1
Reputation: 5084
Just pass a reference to the Column itself like this:
protected void DoSort(DataColumn dc)
{
string columnName = dc.ColumnName;
Type type = dc.DataType;
}
Cheers, CEC
Upvotes: 0
Reputation: 108947
You can use Type
as parameter type. like this
void foo(object o, Type t)
{
...
}
and call
Double d = 10.0;
foo(d, d.GetType());
or
foo(d, typeof(Double));
Upvotes: 6