c# pass method into parameter for logging [duplicate] - c#

This question already has answers here:
Retrieving the calling method name from within a method [duplicate]
(7 answers)
Closed 4 years ago.
I am implementing simple logging, and I would like to do something like below
public int SomeMethod(int x)
{
Log(SomeMethod,"here is a log entry);
}
In the Log method, I would like to parse out the class name from the method and print to the log file the method name and class name.
Is it possible to do something that would look as simple as above or something similar?

you could use nameof if you are using C# 6 or later
public int SomeMethod(int x)
{
Log(nameof(SomeMethod), "here is a log entry");
}

Try this with Reflection
var currentMethodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
var currentCalssName = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name;
Or you can implement your Log method like these
public static void Log<TCallerClass>(string text, [CallerMemberName]string method = "")
{
var callerMethodName = method;
var callerCalssName = typeof(TCallerClass).FullName;
}
Usage : Log<YourClass>("here is a log entry");
public static void Log(string text)
{
var stackFrame = new StackFrame(1, true);
var callerMethodName = stackFrame.GetMethod().Name;
var callerCalssName = stackFrame.GetMethod().DeclaringType.Name;
}
Usage : Log("here is a log entry");

Related

c# is it possible to create extension method for string keyword [duplicate]

This question already has answers here:
What are Extension Methods?
(13 answers)
Closed 2 years ago.
I created an extension method for generating string from System.Guid like this.
public static class Fnk
{
public static string Guid(bool dash = true)
{
return dash ? System.Guid.NewGuid().ToString() : System.Guid.NewGuid().ToString("N");
}
}
I am using it like Fnk.Guid(). I wonder that, is it possible to call it like string.Guid()? If yes, how?
Is it possible to call it like string.Guid()
No. Extension methods allow static methods to be called as if they're instance methods. You're trying to write a static method and allow it to be called as if it's a static method on an unrelated type.
That isn't supported - at least not as of C# 8.
Writing genuine extension methods targeting string is entirely feasible. For example:
public static class PointlessExtensions
{
public static HasEvenLength(this string text) => (text.Length & 1) == 0;
}
Called as:
bool result1 = "odd".HasEvenLength(); // False
bool result2 = "even".HasEvenLength(); // True

Calling class object's function from string in c# [duplicate]

This question already has answers here:
Calling a function from a string in C#
(5 answers)
Closed 4 years ago.
I'm using WPF mvvm pattern anyway if some method got string parameter is this possible calling like
SomeClass1 sc = new SomeClass();
DummyClass2 dc = new DummyClass2();
public void SomeMethod(string param) //param = "SomeMethodName"
{
sc.'param'(dc);
}
The key is calling class object's fuction via param without branch or Data structure mapping.
maybe using reflection.. any good idea?
Yes that's possible via reflection. You can use the Invoke method.
It would look something like this:
MethodInfo method = type.GetMethod(name);
object result = method.Invoke(objectToCallTheMethodOn);
Having said that, in normal circumstances you shouldn't use reflection to call methods in c#. It's only for really special cases.
Here's a full example:
class A
{
public int MyMethod(string name) {
Console.WriteLine( $"Hi {name}!" );
return 7;
}
}
public static void Main()
{
var a = new A();
var ret = CallByName(a, "MyMethod", new object[] { "Taekyung Lee" } );
Console.WriteLine(ret);
}
private static object CallByName(A a, string name, object[] paramsToPass )
{
//Search public methods
MethodInfo method = a.GetType().GetMethod(name);
if( method == null )
{
throw new Exception($"Method {name} not found on type {a.GetType()}, is the method public?");
}
object result = method.Invoke(a, paramsToPass);
return result;
}
This prints:
Hi Taekyung Lee!
7

is a 'field' but is used like a type - C# [duplicate]

This question already has answers here:
What is the syntax for a default constructor for a generic class?
(3 answers)
Closed 6 years ago.
I have to create an implementation of a stack.
I want to create a class that I can use like so:
Stack<string> myStack = new Stack<string>();
myStack.Push("Harold");
myStack.Push("Evie");
myStack.Pop(); // => "Evie"
Here's what I've written so far:
public class Stack<T> {
private T[] stack;
private int stackPointer;
public Stack<T>() {
this.stackPointer = -1;
}
}
But already I am getting this error from VS:
this.stackPointer = -1;
// ERROR: stackPointer is a field but is used like a type.
What does this mean and how do I fix it? (Note I am extremely new to C#)
Try removing the type in the constructor, like this:
public class Stack<T> {
private T[] stack;
private int stackPointer;
public Stack() {
this.stackPointer = -1;
}
}
Take a look at this Microsoft article about generics which actually includes an implementation of a generic stack class.

What is the => operator when not used with a lambda expression? [duplicate]

This question already has answers here:
What does the => operator mean in a property or method?
(7 answers)
Closed 6 years ago.
I was looking at someone's library the other day and they had this:
internal static string BaseUrl => "https://api.stripe.com/v1";
public static string Invoices => BaseUrl + "/invoices";
Isn't the => just acting like an assignment = operator? Wouldn't this be the same:
internal static string BaseUrl = "https://api.stripe.com/v1";
public static string Invoices = BaseUrl + "/invoices";
Never saw this before.
This is a new feature in C# 6.0 called Expression-Bodied, is a syntactic sugar that allows define getter-only properties and indexers where the body of the getter is given by the expression body.
public static string Invoices => BaseUrl + "/invoices";
Is the same as:
public static string Invoices
{
get
{
return BaseUrl + "/invoices";
}
}
You can read more here.
Also you can define methods as well with this syntax:
public void PrintLine(string line) => Console.WriteLine(line);

Print property name (not what you would think) [duplicate]

This question already has answers here:
Get property name and type using lambda expression
(4 answers)
Closed 9 years ago.
This is a cursory question I can't quite answer.
The main program
class Program{
static void Main(string[] args){
Console.WriteLine("Begin");
var myClass = new MyClass();
Util.Print(myClass.Id);
Util.Print(myClass.Server);
Util.Print(myClass.Ping);
Console.WriteLine("End");
}
}
How do I implement the Util.Print method to get this output to the console:
Begin
Id
Server
Ping
End
Assuming you don't want to use strings, the most common answer is via an Expression - essentially emulating the missing infoof; you would have to use something like:
Console.WriteLine("Begin");
var myClass = new MyClass();
Util.Print(() => myClass.Id);
Util.Print(() => myClass.Server);
Util.Print(() => myClass.Ping);
Console.WriteLine("End");
Assuming they are all properties/fields (edit added method-call support):
public static class Util
{
public static void Print<T>(Expression<Func<T>> expr)
{
WriteExpression(expr);
}
public static void Print(Expression<Action> expr) // for "void" methods
{
WriteExpression(expr);
}
private static void WriteExpression(Expression expr)
{
LambdaExpression lambda = (LambdaExpression)expr;
switch (lambda.Body.NodeType)
{
case ExpressionType.MemberAccess:
Console.WriteLine(((MemberExpression)lambda.Body)
.Member.Name);
break;
case ExpressionType.Call:
Console.WriteLine(((MethodCallExpression)lambda.Body)
.Method.Name);
break;
default:
throw new NotSupportedException();
}
}
}
In addition to Marc's answer: here is an article which explains several ways to do what you want to do (one such method uses expressions).
public string Id {
get {
return "Id;"
}
}
Hehe erm, though I assume that's not what you mean :-( The answer will likely be something to do with reflection.
Take a look at http://msdn.microsoft.com/en-us/library/ms173183(VS.80).aspx

Categories