Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Shared VB.NET method to C#

I have the following method written in VB.NET:

Public Shared Function formatClassNameAndMethod(ByVal prefix As String, ByVal stackFrame As StackFrame) As String

        Dim methodBase As MethodBase = StackFrame.GetMethod()

        Return prefix + ":[" + stackFrame.GetMethod().DeclaringType.Namespace + "][" + stackFrame.GetMethod().DeclaringType.Name + "." + methodBase.Name + "] "

End Function

I used a code porting tool to convert it to C#. It produced the following method:

public static string formatClassNameAndMethod(string prefix, StackFrame stackFrame)
{
    MethodBase methodBase = StackFrame.GetMethod();

    return prefix + ":[" + stackFrame.GetMethod().DeclaringType.Namespace + "][" + 
            stackFrame.GetMethod().DeclaringType.Name + "." + methodBase.Name + "] ";
}

Unfortunately, Visual Studio now gives me the following error:

Cannot access non-static method 'GetMethod' in static context

It is complaining about StackFrame.GetMethod() because that method is not static. Why is this happening? I understand what the error is, but I don't understand why I didn't get this in VB.NET. Is there a difference between how Shared in VB.NET and static in C# work? Did the conversion tool not properly convert this?

like image 336
gonzobrains Avatar asked Dec 02 '25 04:12

gonzobrains


1 Answers

GetMethod isn't static. This is what it is telling you.

This means you need to create an instance before you can call the method. Your method already has a StackFrame instance passed in.. and this is merely a case of case sensitivity. Lowercase the S.

public static string formatClassNameAndMethod(string prefix, StackFrame stackFrame)
{ //                                                                     ^^^ this
    MethodBase methodBase = stackFrame.GetMethod();
    //                     ^^ lowercase S
like image 51
Simon Whitehead Avatar answered Dec 04 '25 17:12

Simon Whitehead



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!