Solved

Using Get and Set

Posted on 2013-01-10
24
291 Views
Last Modified: 2013-01-11
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
Comment
Question by:deanlee17
  • 10
  • 7
  • 6
  • +1
24 Comments
 
LVL 13

Expert Comment

by:LIONKING
ID: 38763633
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
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 38763724
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
 
LVL 40

Expert Comment

by:Kyle Abrahams
ID: 38763765
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
Industry Leaders: 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!

 

Author Comment

by:deanlee17
ID: 38766295
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
 
LVL 85

Accepted Solution

by:
Mike Tomlinson earned 400 total points
ID: 38766879
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
 

Author Comment

by:deanlee17
ID: 38766934
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
 
LVL 13

Assisted Solution

by:LIONKING
LIONKING earned 100 total points
ID: 38766943
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
 

Author Comment

by:deanlee17
ID: 38766957
LIONKING, had you seen my above post before you posted? I feel they may have crossed.
0
 
LVL 13

Expert Comment

by:LIONKING
ID: 38766964
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
 
LVL 13

Expert Comment

by:LIONKING
ID: 38766970
Yeah, sorry about the cross posts... I guess you posted while I was writing mine.
0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 38766987
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
 

Author Comment

by:deanlee17
ID: 38767000
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
 

Author Comment

by:deanlee17
ID: 38767017
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
 
LVL 13

Expert Comment

by:LIONKING
ID: 38767028
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
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 38767043
"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
 

Author Comment

by:deanlee17
ID: 38767298
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
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 38767320
Change:

    x = SearchResults.BrokerURL;

To:

    x = BrokerSearch.BrokerURL;
0
 

Author Comment

by:deanlee17
ID: 38767352
Well spotted.
0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 38767375
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
 

Author Comment

by:deanlee17
ID: 38767387
Yes indeed. Right, shared points?
0
 
LVL 13

Expert Comment

by:LIONKING
ID: 38767619
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
 

Author Comment

by:deanlee17
ID: 38767629
Thanks alot LIONKING. Im new to C# so you may well see alot of me kicking around here lol
0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 38767693
I always prefer to share points with all who participated.  People are giving you their time and should be rewarded somehow.  =)
0
 

Author Comment

by:deanlee17
ID: 38767757
Yes, indeed.
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Email security requires an ever evolving service that stays up to date with counter-evolving threats. The Email Laundry perform Research and Development to ensure their email security service evolves faster than cyber criminals. We apply our Threat…
Attackers love to prey on accounts that have privileges. Reducing privileged accounts and protecting privileged accounts therefore is paramount. Users, groups, and service accounts need to be protected to help protect the entire Active Directory …

713 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question