Home > other >  How is it possible to have a non-abstract method in a class without declaring a body?
How is it possible to have a non-abstract method in a class without declaring a body?

Time:10-28

I am learning Asp.net MVC and I came to this point where a controller action calling the view() method in return section. When I clicked f12 on view() method and go to definition, I saw that this is a method in class "controller" in System.Web.Mvc namespace that has no body like many other methods of this class. But how is it possible to have a non-abstract method without a body?

protected internal ViewResult View();

CodePudding user response:

You can have a non abstract method with an empty body, but you can't have a non abstract method without a body at all.

This code compiles and it's an example of a method with an empty body. Notice that this is only possible if the return type is void.

// this code compiles
public class FooClass 
{
  // method with an empty body. Notice the void return type
  public void BarMethod() 
  {
  }
}

The following code doesn't compile and doesn't make sense too:

// this code does not compile
public class FooClass 
{
  // you can't have a non abstract method with no body at all
  public void BarMethod();
}

I think that you are being confused by the F12 key behavior inside of Visual Studio.

F12 is a shortcut for the Go to Definition command in Visual Studio. The View method is defined outside of your source code (it is part of the ASP.NET framework), so as documented here the behavior of the Go To Definition command is showing the method metadata. That's why when you press F12 you see only the method signature and not the full method body.

As a sidenote Visual Studio has some decompiling capabilities. They are not enabled by default, but you can enable them easily. Refer to this documentation for the details. Once you have enabled the decompiler, you will be able to see the decompiled source code for methods defined in nuget packages and framework assemblies.

  • Related