Home > Software engineering >  C# Error CS0426 coming up when it shouldn't be VS2022
C# Error CS0426 coming up when it shouldn't be VS2022

Time:12-03

I'm getting the error

CS0426 "the type name 'GetRequest' does not exist in the type 'Request'

when I'm quite sure that it does. I don't understand what I possibly did wrong here. Here's the code I'm working with:

public class Request
{
    public static Request GetRequest()
    {
        return null;
    }
}

In this class you can clearly see that GetRequest does infact exist within the type 'Request'. However when I try and use this method I get an error saying that it doesn't exist.

This line generates the error I have been getting:

Request req = new Request.GetRequest();

CodePudding user response:

The error you are seeing is because the GetRequest method is not a constructor for the Request class, but rather a static method. In order to call this method, you need to use the class name instead of the new keyword, like this:

Request req = Request.GetRequest(msg);

Alternatively, you can create a new instance of the Request class using the constructor, and then call the GetRequest method on that instance, like this:

Request request = new Request();
Request req = request.GetRequest(msg);

Note that in this case, you will need to modify the GetRequest method to make it non-static, like this:

public Request GetRequest(String request)
{
    if (string.IsNullOrEmpty(request)) { return null; } //return null if the string is empty or nothing

    String[] tokens = request.Split(' ');
    String type = tokens[0];
    String url = tokens[1];
    String host = tokens[4];

    return new Request(type, url, host);
}

CodePudding user response:

new Request.GetRequest(msg); You're trying to create an instance of the type Request.GetRequest here, which in fact does not exist, what you probably wanted is Request.GetRequest(msg) calling the static method GetRequest in the Request class.

  •  Tags:  
  • c#
  • Related