0

I have a property of type string. Any value must be placed in it: string-> string, number-> string, date> string with regional date display, boolean-> string with boolean representation. Do I need to create a function for each type? It turns out a lot of code, since the numeric types in C # are 10:

SetValue(int InputValue) {}
SetValue(uint InputValue) {}
SetValue(long InputValue) {}
SetValue(ulong InputValue) {}
Nik Volk
  • 47
  • 6
  • "Do I need to create a function for each type?" - ideally, yes. How else will people know what types are actually accepted? (Any answer to my rhetorical question saying "check the documentation" is missing the point...) – Dai Sep 08 '21 at 04:47
  • Thanks for the orientation. I just started doing big programming, so I want to write correct (ideally) code from the very beginning. – Nik Volk Sep 08 '21 at 05:01

1 Answers1

1

um... You don't need to create function for each type. Just use generic method.

To avoid boxing, not using object type is recommended.

you can write as follow.

    private void SetValueAsString<T>(T value)
    {
        // As Dai said, ToString() is not robust.
        StringProperty = value.ToString();
    }
ggzerosum
  • 56
  • 4
  • 1
    If you're going to rely on `ToString()` then consider adding a constraint `where T : IConvertible`. However this still has _a bad code-smell_ about it... – Dai Sep 08 '21 at 04:48
  • Yes, i agree. ToString() is not robust. I found another. See this answer : https://stackoverflow.com/questions/2922855/how-to-convert-string-to-any-type – ggzerosum Sep 08 '21 at 04:54