user9993
user9993

Reputation: 6170

C# Unable to create class level object

I have a class, in which I want to create an instance of an XDocument. In the constructor I need to call the "Load" method, but for some reason it is not available to call.

For example:

class MyClass
{
    private XDocument xmlResponse;

    public MyClass(string url)
    {
        xmlResponse.Load(url);
    }
}

I get the error "cannot be accessed with an instance reference; qualify it with a type name instead"

So I tried "MyClass.xmlResponse.Load(url)" but I'm getting the same error.

What is the proper way of calling the method?

Upvotes: 0

Views: 223

Answers (3)

Priya
Priya

Reputation: 1

private XDocument xmlResponse;
xmlResponse = new XDocument(); 

try this. object has to be created before accessing xmlResponse

Upvotes: -1

Selman Genç
Selman Genç

Reputation: 101681

You want:

public MyClass(string url)
{
    xmlResponse = XDocument.Load(url);
}

Load method is a static method on XDocument class, so you can't call it via an instance of XDocument.

Upvotes: 3

p.s.w.g
p.s.w.g

Reputation: 149020

The XDocument.Load method is static, so you have to call it statically. Try this:

public MyClass(string url)
{
    xmlResponse = XDocument.Load(url);
}

Further Reading

Upvotes: 6

Related Questions