[Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 300
  • Last Modified:

Using Get and Set

Hi guys,

Ok So I have the following class....

public class SearchResults
    {
        public string BrokerURL { get; set; }
    }

Open in new window


I assign a value like this....

SearchResults BrokerSearch;
BrokerSearch = new SearchResults ();
BrokerSearch.BrokerURL = "XYZ";

Open in new window


But then how do I call this back in another class or area of code?

I tried searchresult.  <then it gives me a choice of equals or referenceequals, not BrokerURL>?

Many Thanks,
Dean.
0
deanlee17
Asked:
deanlee17
  • 10
  • 7
  • 6
  • +1
2 Solutions
 
LIONKINGCommented:
I don't know if I understand your question correctly, but have you tried:

SearchResults BrokerSearch;
BrokerSearch = new SearchResults ();
BrokerSearch.BrokerURL = "XYZ";

string classUrl;
classUrl = BrokerSearch.BrokerURL;

Open in new window

0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
Right..."BrokerSearch" represents a specific instance of your SearchResults class.  If you want to access that instance from somewhere outside the scope of where it was declared then you have PASS A REFERENCE to that instance to where you need it.
0
 
Kyle AbrahamsSenior .Net DeveloperCommented:
It would be better to look at the longhand version:

class foo

private string _BrokerURL;

public string BrokerURL
{

  get
   {
     return _BrokerURL;
    }
 
  set
    {
               _BrokerURL = value;
    }
}

}



When you do the {get; set;} you essentially get the same thing as the above.

The set is called whenever you are assigning the property, the get whenever you are retrieving the property.  (Note you can create a readonly property by only having a get).

as LionKing noted:

foo BrokerSearch;
BrokerSearch = new foo ();
BrokerSearch.BrokerURL = "XYZ";  // the set is called during this line.

string x;
x = BrokerSearch.BrokerURL; // the get is called.


Note you can add logic if you take the long approach.

EG:

// don't allow an empty string.
if (value != "")
   _BrokerSearch = value;
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
deanlee17Author Commented:
Ok so for the GET method I have....

public partial class MainWindow : Window
    {
             public void  brokerresults()
                {
                        string x;
                        x = SearchResults.BrokerURL; 
                  }
    }

Open in new window


I get the error... An object reference is required for the non-static field, method or property. I assume this links to what IdelMinds was saying about needing to pass a reference?

Thanks.
0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
Not exactly.  Show us where you are declaring your instance of SearchResults, AND also show us where you want to access it.  Then we can show you how to pass a reference.

If you need it only at Form level, then declare it there like this:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class MainForm : Form
    {

        private SearchResults BrokerSearch; // <-- accessible from anywhere in the Form

        public MainForm()
        {
            InitializeComponent();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            BrokerSearch = new SearchResults ();
            BrokerSearch.BrokerURL = "XYZ";
        }

        private void button1_Click(object sender, EventArgs e)
        {
            label1.Text = BrokerSearch.BrokerURL;
        }

    }

    public class SearchResults
    {
        public string BrokerURL { get; set; }
    }

}

Open in new window

0
 
deanlee17Author Commented:
Ok so I currently have the following in one window (ive cut some code away)..

namespace WebLinks
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            //NetComponentsBrowser.Navigate("http://www.netcomponents.com/results.htm?t=f&r=1&pn1=ABC");
        }

        private void btwSearch_Click(object sender, RoutedEventArgs e)
        {
  SearchResults BrokerSearch;
            BrokerSearch = new SearchResults ();
            BrokerSearch.BrokerURL = "XYZ";
}

 public void  brokerresults()

        {

           string x;
           x = SearchResults.BrokerURL;
}

Open in new window


Then I went Add> Class and put this in a new class....

namespace WebLinks
{
    class SearchResults
    {
        private string _BrokerURL;
        public string BrokerURL
        {
            get { return _BrokerURL; }
            set { _BrokerURL = value; }

        }
    }

}

Open in new window

0
 
LIONKINGCommented:
I still don't understand exactly what you want to do.

First things first... You are declaring the class correctly, you specify that the class has one private member (BrokerURL) and this member has its get/set methods.
public class SearchResults
    {
        public string BrokerURL { get; set; }
    }

Open in new window


This will enable you to instantiate the class (i.e. declare a variable of type SearchResults) and use it in your program. This variable, as any other in your program, has a determined scope that depends on where you declare it. So, if you need it throughout your entire form you would declare it at the form level, if this variable is only needed in one method, then you would declare it at that level.

If you plan on passing this variable to another form or class, one thing you could do is create a "property" for that class/form that accepts a SearchResults type. This is done by creating a "Setter" in that class.

If the only thing you need is to be able to access your variable throughout one specific class (form) you can do it by instantiating your class (declaring the variable) at the form level.

I will not post any code because Idle_Mind already showed how it's done, I'm just explaining a little bit (more or less) how it works and asking what exactly it is that you need/want.

Hope it helps.
0
 
deanlee17Author Commented:
LIONKING, had you seen my above post before you posted? I feel they may have crossed.
0
 
LIONKINGCommented:
This will not work because you're trying to access a variable that is out of scope.
Look at where your variable is declared and where you want to use it.

namespace WebLinks
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            //NetComponentsBrowser.Navigate("http://www.netcomponents.com/results.htm?t=f&r=1&pn1=ABC");
        }

        private void btwSearch_Click(object sender, RoutedEventArgs e)
        {
  SearchResults BrokerSearch; // <<<--- By declaring your variable here, it will only be available within the btwSearch_Click function/method.
            BrokerSearch = new SearchResults ();
            BrokerSearch.BrokerURL = "XYZ";
}

 public void  brokerresults()

        {

           string x;
           x = SearchResults.BrokerURL; // <<< --- this variable doesn't exist in this method because it was never declared here. It's out of scope.
}

Open in new window


As stated before, if you want to access the variable throughout your entire form class, you need to declare it at the form level. Something like this:

namespace WebLinks
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        SearchResults BrokerSearch; // Variable declared on the form level, thus it's available throughout the entire form class

        public MainWindow()
        {
            InitializeComponent();
            //NetComponentsBrowser.Navigate("http://www.netcomponents.com/results.htm?t=f&r=1&pn1=ABC");
        }

        private void btwSearch_Click(object sender, RoutedEventArgs e)
        {
            BrokerSearch = new SearchResults ();
            BrokerSearch.BrokerURL = "XYZ";
}

 public void  brokerresults()

        {
           string x;
           x = SearchResults.BrokerURL;
}

Open in new window


By declaring the variable at the form/class level, you will have it available at any part within this class/form.
0
 
LIONKINGCommented:
Yeah, sorry about the cross posts... I guess you posted while I was writing mine.
0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
In your code here:
        private void btwSearch_Click(object sender, RoutedEventArgs e)
        {
            SearchResults BrokerSearch;
            BrokerSearch = new SearchResults ();
            BrokerSearch.BrokerURL = "XYZ";
        }

Open in new window


"BrokerSearch" is declared within the btwSearch() method, which means it is only accessbile within that method.  This is known as SCOPE:
http://msdn.microsoft.com/en-us/library/ms973875.aspx

If you want to access it outside that method, then declare it at the class level:
        private  SearchResults BrokerSearch;

        private void btwSearch_Click(object sender, RoutedEventArgs e)
        {
            BrokerSearch = new SearchResults ();
            BrokerSearch.BrokerURL = "XYZ";
        }

Open in new window


Now you'll be able to use "BrokerSearch" from anywhere within that class.

If you need to access it from a different class, then we'd pass a reference to that class.  Let us know if that is the case.
0
 
deanlee17Author Commented:
Ok excellent, I do understand what you are saying.

In my mind I thought using a new class with Get \ Set you could just store variables from anywhere in your code and call them back at any time simply by calling the class name and then the member i.e SearchResults.BrokerURL
0
 
deanlee17Author Commented:
Idle_Mind,

Thanks for the example, it is all coming together now in my head. Could you just give me an example of accessing it through a different class so as I can get the complete picture.

Many thanks guys, appreciate your patients as i'm probably asking some stupid questions.
0
 
LIONKINGCommented:
In my mind I thought using a new class with Get \ Set you could just store variables from anywhere in your code and call them back at any time simply by calling the class name and then the member i.e SearchResults.BrokerURL

Just to clarify.... This can be done... You can do it by using Static Classes, as they don't need to be instantiated and will return the same value all the time.

Check the link for more info:

http://msdn.microsoft.com/en-us/library/79b3xss3(v=vs.80).aspx
0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
"In my mind I thought using a new class with Get \ Set you could just store variables from anywhere in your code and call them back at any time simply by calling the class name and then the member i.e SearchResults.BrokerURL"

That would be accomplished by using the "static" modifier against your BrokerURL() property:
http://msdn.microsoft.com/en-us/library/f4ewhdb8(v=vs.80).aspx
0
 
deanlee17Author Commented:
Ok so we now currently have....

namespace WebLinks
{
    public partial class MainWindow : Window
    {
        SearchResults BrokerSearch;

        public MainWindow()
        {
            InitializeComponent();
        }

         private void btwSearch_Click(object sender, RoutedEventArgs e)
        {
            BrokerSearch = new SearchResults ();
            BrokerSearch.BrokerURL = "XYZ;
        }
     
         public void  brokerresults()
        {
           string x;
           x = SearchResults.BrokerURL; 
        }
  }
}
   

Open in new window


It is still not liking ' x =  SearchResults.BrokerURL;' saying

'An object reference is required for the non static field, method or property'.

I cant see where ive gone wrong here from what you have said?

Thanks.
0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
Change:

    x = SearchResults.BrokerURL;

To:

    x = BrokerSearch.BrokerURL;
0
 
deanlee17Author Commented:
Well spotted.
0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
To use the first approach you'd implement the "static" modifier.  If that approach is used, then you don't need the variable declaration at class level since no instance of the class is required.
0
 
deanlee17Author Commented:
Yes indeed. Right, shared points?
0
 
LIONKINGCommented:
I guess Idle_Mind helped you out a lot giving you code examples and whatnot.
Give him the points or split them as you think is fair, I'm ok with whatever you decide.

No hard feelings... :)

Glad you worked it out!
0
 
deanlee17Author Commented:
Thanks alot LIONKING. Im new to C# so you may well see alot of me kicking around here lol
0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
I always prefer to share points with all who participated.  People are giving you their time and should be rewarded somehow.  =)
0
 
deanlee17Author Commented:
Yes, indeed.
0

Featured Post

Prepare for your VMware VCP6-DCV exam.

Josh Coen and Jason Langer have prepared the latest edition of VCP study guide. Both authors have been working in the IT field for more than a decade, and both hold VMware certifications. This 163-page guide covers all 10 of the exam blueprint sections.

  • 10
  • 7
  • 6
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now