MisterNad MisterNad -3 years ago 57
C# Question

c# Method redirect or overload (possibly with arguments)

I'm not sure if this is possible, but I'm essentially looking for a class constructor redirect.

An example of what I'm attempting:

public class Test
{
public Test() : TestFromOther();
//public Test() => TestFromOther();
public TestFromOther() { return 'this' with some stuff done here }
//another case might be => TestFromOther(defaultparam)
}


I'm trying to do this so that even if the base constructor is called, it redirects to my method.

(I don't want to just put a call to TestFromOther() inside the body of the constructor.. I'm specifically looking for the
:TestFromOther()
or
=>
operator.. I've seen it before but for the life of me cannot remember how it's done)

EDIT: It's mostly for cleanliness and readability, thus having the Logger.GetCurrentClassLogger();

public class Logger {
private string _callerClass;

// obviously this doesn't function, but is the ideal end product
//public Logger() => GetCurrentClassLogger();
// Ideally I want the constructor to be this function and if a user, for
// whatever reason does call the empty constructor, it goes to this func
public Logger GetCurrentClassLogger() {
StackFrame[] sf = new StackTrace().GetFrames();
string callerName = "";
foreach (StackFrame f in sf) {
if (f == sf[0])
continue;
if (f.GetMethod().Name == ".ctor") {
callerName = f.GetMethod().ReflectedType.Name;
break;
}
callerName = f.GetMethod().Name;
break;
}
this._callerClass = callerName;
return this;
}
}


I trimmed this down about as far as I could for use as an example

Answer Source

You can "chain" constructors. it's not a redirection.

public class Test
{
    public Test() : this("defaultParam") {}
    public Test(string stringParam) { }
}

It will execute Test(string stringParam) first and then Test()


Edit per the comments and the edited question

static method is the way to achieve what you like:

public static Logger GetCurrentClassLogger() {...}

and the instantiation:

var logger = Logger.GetCurrentClassLogger(); // no new key word here
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download