Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending DataType As An Argument?

Tags:

methods

c#

types

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. 
like image 397
sooprise Avatar asked Apr 11 '11 18:04

sooprise


2 Answers

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));
like image 57
Bala R Avatar answered Sep 24 '22 20:09

Bala R


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

like image 1
Brook Avatar answered Sep 26 '22 20:09

Brook