C # - method behavior that depends on the expected type

Is it possible to write in a C # method in such a way that when I write

 String contestId = getParameter("contestId")

      

I am getting contestId on line, but when I write:

 int contestId = getParameter("contestId")

      

am I getting contestId parsed to an integer?

This is a simple example of what I am trying to achieve.

+1


a source to share


5 answers


It is not possible to overload methods based on their return type alone. However, you can enter a general parameter:

T getParameter<T>(string input) {
    // ... do stuff based on T ...
}

      

And if you are using C # 3.0 you can use this method like:



var str = getParameter<string>("contestid");
var integer = getParameter<int>("contestid");

      

in such a way that the actual type is only one time.

+15


a source


One thing you can do is return a separate object that has implicit conversion operators for both int and string. This will be pretty close to the behavior you are asking for.

I wouldn't do this in practice. Implicit conversions usually cause more problems than they are worth.



Instead, add a generic parameter as Mehrdad showed:

var str = getParameter<string>("contestid");
var integer = getParameter<int>("contestid");

      

+3


a source


I prefer this approach, it reads well.

Public Class ResultProxy
{
  Private Object _Obj
  Public ResultProxy(Object O)
  { _Obj = O; }

  Public T As<T>()
  { return (T)_Obj; }
}

      

...

Public ResultProxy getParameter("contestId")
{
// your method code
   return new ResultProxy(YourPersonalFavorateReturnType);
}

      

...

String s = getParameter("contestId").As<String>();

      

+1


a source


First, the answer is not many people have mentioned. What for? Do I need to attribute the result of a method? For example, you have

int getValue()
{
  return 4;
}

getValue();

      

Answer: yes, it is possible, so the compiler does not know which method you intend to call on its return type.

Personal opinion here, but I would suggest something like

public string getContestIdAsString(string ConetestId);

public int getContestIdAsInt(string ContestId);

      

It's very obvious what everyone is doing, and you've got around your problem. If there is anything that I am missing.

+1


a source


public T GetParameter<T>(string parameterName)
{
   //Do work
   return value
}

string contestId = getParameter<string>("contestId")
int contestId = getParameter<int>("contestId")

      

This is an example of your best bet.

0


a source







All Articles