0

I'm fairly new to C# and wondered if it is possible, to call a function based on the variable it is assigend to? I'm know i could overload the function and pass the variable as parameter, but I just wondered if this is possible.

Example, convert a value from a datarow to the datatype it is assigned to.

private int myint;
private string mystr;
private DateTime mydate;

myint = assign(datarow, "number");

// calls this
private int assign (DataRow r, string columnname)
{
    return Convert.ToInt32(r[columnname]);
}

mystring = assign(datarow, "name");

// calls this
private string assign (DataRow r, string columnname)
{
     return Convert.ToString(r[columnname]);
}
Mister 832
  • 1,177
  • 1
  • 15
  • 34
  • That code isn't valid, you can't return values when the functions return type is `void`. –  Aug 01 '16 at 16:49
  • 2
    It's possible if you use `out` arguments instead of return types. – Ivan Stoev Aug 01 '16 at 16:50
  • Further to @rene 's answer, the closest you will find to what you are looking for is generics: https://msdn.microsoft.com/en-us/library/512aeb7t.aspx although as rene points out) is not possible. – Murray Foxcroft Aug 01 '16 at 16:51
  • sorry, corrected the code. It might be a duplicate, thank you for this. However, as a newbie i find them a bit hard to understand. But i will look further into the links posted. – Mister 832 Aug 01 '16 at 16:53
  • You can create Generic function and handle the situation. Sample link: https://msdn.microsoft.com/en-us/library/ms379564(v=vs.80).aspx – Vijai Aug 01 '16 at 17:45

1 Answers1

2

Return type issues aside. You can not do this the function declarations collide. The compiler needs a unique signature for each method it compiles. It generates those signatures using the function name and the parameters. It does not care about return types.

Marissa
  • 430
  • 3
  • 12