I have 2 methods that are very similar.
public string GetMyObjectInJson(parameters)
{
MyObject TheObject = new MyObject();
...lots of work here
Javascript Serializer = new Javascript Serializer();
return Serializer.serialize(TheObject);
}
public MyObject GetMyObject(parameters)
{
MyObject TheObject = new MyObject();
...lots of work here
return TheObject;
}
How should I rewrite this so that I only have one method that can return 2 different types: sometimes a string and sometimes an object.
Thanks.
You shouldn’t. You should have two methods, so that it’s clear from the calling code what you want and what you’ll get back.
You can, however, use one method to do most of the work:
However, this suggests that actually the
MyObjectclass should potentially have aSerializeToJsonmethod, so callers would write:Note that even if you couldn’t chain one method directly to another, you could have one private method containing the common work, which would be called from both the public methods. You shouldn’t make your public API less clear when you can just refactor your implementation.