Home > OS >  Accessing a property of a non-static class without assigning it to a variable
Accessing a property of a non-static class without assigning it to a variable

Time:09-29

I am writing a custom automation framework using Selenium, C# and Page Object Pattern. I am trying to extract some values from the pages without stopping the statement.

Basically I want to turn this:

    var page = Login()
        .OpenPage();

    page.Remember(page.Title);
    page.MoreActions()
        .MoreNavigation();

into this:

    var page = Login()
        .OpenPage()
        .Remember(???.Title)
        .MoreActions()
        .MoreNavigation();

Not sure if it is possible and how I could access the class at that point.

Notes:

  • All the methods return pages
  • Making the classes static and using the class name is not an option as we have our page structure based on inheritance and overloading methods.
  • Creating RememberTitle methods on all the pages is not an option because I want to remember the value into a Dictionary of parameters and such a parameter cannot be passed by reference.

Update: As per comments I tried implementing a lamda expression:

  .Remember(parameters["Title"], p => p.Title);
public virtual NavPage<T> Remember(TestParameter parameter, Expression<string> value)
        {
            parameter.Value = value.Compile();
            return this;
        }

This does not work as I am not sure who p should be. The question here would be: is there any way (keyword?) to point to the page returned by the previous statement?

CodePudding user response:

The only way to access a non-static variable from a static method is by creating an object of the class the variable belongs to.

CodePudding user response:

What you can do is to write an extension method to achieve your desired result. Let's say the page that you mentioned is of type Page & the Title that you've mentioned is of type string. Then you can have the following extension method:

public static Page Remember(this Page page, Func<Page, string> getTitle)         
{             
    var title = getTitle(page);             
    // Use the title
    page.Remember(page.title);

    // Return page object for further chaining
    return page;         
}

Then you can use this extension method the following way:

 var page = Login()
    .OpenPage()
    .Remember(p => p.Title)
    .MoreActions()
    .MoreNavigation();
  • Related