How I can get the calling methods in C# [duplicate] - c#

This question already has answers here:
How can I find the method that called the current method?
(17 answers)
Closed 9 years ago.
Possible Duplicate:
How can I find the method that called the current method?
I need a way to know the name of calling methods in C#.
For instance:
private void doSomething()
{
// I need to know who is calling me? (method1 or method2).
// do something pursuant to who is calling you?
}
private void method1()
{
doSomething();
}
private void method2()
{
doSomething();
}

from http://www.csharp-examples.net/reflection-calling-method-name/
using System.Diagnostics;
// get call stack
StackTrace stackTrace = new StackTrace();
// get calling method name
Console.WriteLine(stackTrace.GetFrame(1).GetMethod().Name);

You almost certainly don't want to do this. A caller should never know who is calling it. Instead, the difference between the two callers should be abstracted into a parameter, and passed into the method being called:
private void doSomething(bool doItThisWay)
{
if (doItThisWay)
{
// Do it one way
}
else
{
// Do it the other way
}
}
private void method1()
{
doSomething(true);
}
private void method2()
{
doSomething(false);
}
This way, if you add a method3, it can either doSomething one way or the other, and doSomething won't care.

Related

Chaining Class Constructors at the end [duplicate]

This question already has answers here:
Call one constructor from another
(13 answers)
Closed 5 months ago.
I have some old code from someone else that I need to fix so it builds again and one issue that I don't know how to fix, is constructor chaining. It looks something like this:
class Foo(){
public Foo()
{
int i = /*block of code*/;
this (i);
}
public Foo(int i)
{
//..
}
}
The error comes at the this (i); line where it says Method, delegate, or event is expected. Basically it no longer allows you to use this as just a constructor anymore. Maybe it did in older version of C#.
What would be the appropriate way to fix this? I can replace public Foo() with public Foo(): this(i) but then it doesn't recognize the variable i anymore.
If you want to run a block of code before calling this(), you can use a static method:
class Foo()
{
public Foo() : this(SomeMethod())
{
}
public Foo(int i)
{
//..
}
private static int SomeMethod()
{
int i = /*block of code*/;
return i;
}
}
Note that you can't mutate the instance state in SomeMethod(), but such logic should probably be in Foo(int i) anyway.

Since we have multicast delegates, why do we need events? [duplicate]

This question already has answers here:
Difference between events and delegates and its respective applications [closed]
(10 answers)
Closed 3 years ago.
I was asked this question in an interview, and either I'm suffering from brain-lock or just plain dumb, but I didn't have an answer.
Couple of reasons why we need events:
Restricting scope, you do not want to expose your events, like you can for your delegates.
You can have events as fields in your interfaces and not delegates
Example below:
Class Printer
{
public event EventHandler Print;
public void Start()
{
OnPrint();
}
protected virtual void OnPrint()
{
Print?.Invoke(this,EventArgs.Empty);
}
}
class Program
{
static void Main(string[] args)
{
//When Print is an EventHander
var printer = new Printer();
printer.Print += PrintEvent;
printer.Start();
//If Print was a delegate this is possible, else you get compile time errors
printer.Print(null,null); // Events will not allow to have a direct invoke
printer.Print = null; //You cannot assign a null to an Event Handler
}
private static void PrintEvent(object sender, EventArgs e)
{
System.Console.WriteLine("Printing event");
}
}

Will using destroy data if return will be inside [duplicate]

This question already has answers here:
What happens if i return before the end of using statement? Will the dispose be called?
(5 answers)
Closed 4 years ago.
While working on my project, I was wondering, will using auto-destruct data if return will be inside of a using.
Example block of code:
using(ManagedObject obj = new ManagedObject())
{
int usualNumber = 0;
// some magic stuff
...
// magic stuff ends
return usualNumber; // return goes inside of 'using' brackets
}
And here is the question, will our ManagedObject which implements IDisposable be disposed by 'using' statement?
using statement can be seen as try and finally combination.
Your code is equivalent to:
ManagedObject obj = new ManagedObject();
try
{
int usualNumber = 0;
// some magic stuff
...
// magic stuff ends
return usualNumber;
}
finally
{
if (obj != null)
((IDisposable)obj ).Dispose();
}
I assume, that the answer to your question can be seen thanks to this code sample.
using is a Syntactic sugar, it need to contain an object which implements IDisposable interface when you leave the using scope .net will call the IDisposable.Dispose method Automatically.
Here is a sample c# online
when the program leave Test method. .net will call IDisposable.Dispose method Automatically
Yes, It will call the Dispose() function implemented by the IDisposable interface
class Program
{
static void Main(string[] args)
{
new Test().TestIt();
Console.Read();
}
}
class Test
{
public int TestIt()
{
using (ManagedObject obj = new ManagedObject())
{
int usualNumber = 0;
return usualNumber;
}
}
}
internal class ManagedObject : IDisposable
{
public void Dispose()
{
Console.WriteLine("Disposed");
}
}
Yes, even if you return from inside the using block, it will still call Dispose on obj.
Note that returning the usualNumber is perfectly fine, but if you were to return obj, that could be a problem because you would be returning a "disposed" object.
(Technically, objects could be usable after calling Dispose. For example, you could implement a Dispose that does nothing. But generally, most Dispose implementations would put the object in an unusable state).

Should make static method when possible? [duplicate]

This question already has answers here:
Method can be made static, but should it?
(14 answers)
Closed 8 years ago.
Consider the following class:
public class Extractor
{
public IService service;
public Extractor(IService service)
{
this.service = service;
}
public void DoSth()
{
var sampleMethodInfo = this.service.GetMethodInfo();
var version = ExtractAvailableMethodVersion(sampleMethodInfo);
// other stuff
}
private int ExtractAvailableMethodVersion(MethodInfo methodInfo)
{
var regex = new Regex(MIGRATION_METHD_NAME_EXTRACT_VERSION);
var matcher = regex.Match(methodInfo.Name);
return Convert.ToInt32(matcher.Groups[1].Value);
}
}
Resharper hints to make ExtractAvailableMethodVersion static. So my question is - should I make static method everywhere it's possible (like in the example ablove)? Is any performance difference when calling static / non-static method in such a case? Or is it only "code-style rule" to make static method when not using instance members?
You don't make methods static just when possible, you do it when it makes sense, ie. what method does is not related to specific instance, but to a class in general.
Evaluate whether this is the case here, but you are not using current instance anywhere in the method, so above might be the case.

How to create an awaitable class? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Can constructors be async
I have a class Example that pulls several information from the internet on creation.
public class Example
{
string information;
public Example()
{
//Pull information
}
}
Now I would like to let Example become awaitable because it is important that Example is created before continuing the part after creation.
public async void SetupSomething()
{
Example ex = new Example();
await ex;
// Do something with ex
}
How can I do this?
You could do that, but I think that's not a good approach, because there is nothing forcing the await before you start using the instance.
I think a good idea would be to create static asynchronous method that creates your object. Something like:
class Example
{
private Example()
{
}
private async Task InitializeAsync()
{
// get the required data asynchronously here
}
public static async Task<Example> CreateAsync()
{
var result = new Example();
await result.InitializeAsync();
return resul;
}
}
Well, the constructor should wait until it is done doing it's stuff. After all, the thread use to create it is from the method that calls it.
However, what I think would be very important, is to show us what that constructor is doing. There's a good chance it is calling something somewhere that start another thread and doesn't wait for it to resolve, making the constructor returns while not having all the "information" you are talking about.
Might be similar to: C# : Blocking a function call until condition met

Categories