cannot use variable declared class in the function inside the same class. why ?
-
28-09-2019 - |
Question
i have declared a variable in the class 'Main' with name 'context2'. But i cannot use the variable inside the function 'Main_Load'. what am i doing wrong ?
using System;
using System.Windows.Forms;
using Soapi;
using Soapi.Domain;
namespace SO_Console_Client
{
public partial class Main : Form
{
const string apiKey = "*************";
var context2 = new ApiContext(apiKey).Initialize(false);
public Main(String GravatarURL, User user)
{
InitializeComponent();
pictureBox1.Load(GravatarURL); //Loads the Gravatar image from the url
//set the reputation details
lblRep.Text = String.Format("Reputation: {0}", user.Reputation);
//Sets the badge details
lblBadge.Text = String.Format("Badges: gold={0} silver={1} bronze={2}", user.BadgeCounts.Gold, user.BadgeCounts.Silver, user.BadgeCounts.Bronze);
groupBox1.Text = user.DisplayName.ToString();
}
private void Main_Load(object sender, EventArgs e)
{
Soapi.Queries.QuestionsUnansweredQuery query = context2.Official.StackOverflow.Questions.Unanswered;
foreach (Question q in query)
{
try
{
Console.WriteLine(q.Title.ToString());
//Console.WriteLine(q.Body.ToString());
}
catch (System.NullReferenceException ex)
{
}
}
}
}
}
Solution
Implicit typing doesn't work with fields; it only works with local variables.
I think this is what your real intention is:
ApiContext context2 = new ApiContext(apiKey);
public Main(String GravatarURL, User user)
{
context2.Initialize(false);
...
}
In the highly unlikely case that ApiContext
is some sort of fluent-interface for which ApiContext.Initialize(bool)
returns a differentApiContext
object, this should be what you want:
ApiContext context2 = new ApiContext(apiKey).Initialize(false);
although it would be much clearer if you did:
ApiContext context2;
public Main(String GravatarURL, User user)
{
context2 = new ApiContext(apiKey).Initialize(false);
...
}
I really doubt that, though.
OTHER TIPS
This can't compile. var
-type variable declarations cannot be at the class level, only the method level.
There are technical issues with allowing var to be used with fields. This is why a concrete type must be specified. Here is an explanation of the issues from Eric Lippert: