Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

General function for all value types in class

Tags:

c#

.net

winforms

I'm trying to accomplish the following within a class:

public void Test(var input)
{
    WriteToFile(input.ToString());
}

private void WriteToFile(string input)
{
    .....
}

But the 'var' statement can not be used within a class. So I'm wondering what the easiest way is to accomplish the same thing as above.

One solution would be to create a function for each value type, but that must be more trouble than necessary:

public void Test(string input)
{
    WriteToFile(input);
}

public void Test(int input)
{
    WriteToFile(input.ToString());
}

public void Test(double input)
{
    WriteToFile(input.ToString());
}

private void WriteToFile(string input)
{
    .....
}

EDIT: When giving it some more thought I understood that this wasn't really the answer to my problems. I'm posting a new question that has more thought behind it. I'm not gonna delete this question though since someone else might find this usefull.

like image 385
Robin Avatar asked Jan 20 '26 18:01

Robin


2 Answers

Just pass object and call ToString() on it:

public void Test(object input)
{
    WriteToFile(input.ToString());
}
like image 120
gzaxx Avatar answered Jan 23 '26 06:01

gzaxx


public void Test<T>(T input)
{
    WriteToFile(Convert.ToString(input));
}
like image 21
burning_LEGION Avatar answered Jan 23 '26 08:01

burning_LEGION



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!