I try to use data after I downloaded it from an API. Example of my code:
private int id;
public MainPage()
{
InitializeComponent();
SomeFunction();
}
public void SomeFunction()
{
DownloadFromAPI("url to api");
MessageBox.Show(id.ToString()); //<< Returns 0
}
public void DownloadFromAPI(DownloadStringCompletedEventArgs url)
{
//code to retrieve data (singel id)
id = Int16.Parse(data);
MessageBox.Show(id.ToString()); //<< Returns the correct number, like 14
test();
}
private void test()
{
MessageBox.Show(id.ToString()); //<< Even Returns the correct number 14
}
How is it possible to load the id information after DownloadFromAPI("url to api"); is finished. so i get the right number (14) instead of 0?
I suspect your method actually looks like this:
public void DownloadFromAPI(...)
{
int id = Int16.Parse(data);
MessageBox.Show(id.ToString()); //<< Returns the correct number, like 14
}
That's declaring a new local variable within the method, rather than assigning a value to the instance variable.
However, personally, I'd often prefer to write the method to return the value instead:
public int DownloadFromApi(...)
{
return Int16.Parse(data);
}
Of course if this really is natural state within the object, it may make sense - but often it can be simpler to write code which just computes a value and returns it, than getting into mutation territory.
Whether you keep the 'id' in a local class member or not, either way, you should generally have your methods act upon input and produce any pertinent output, without referencing things outside of their local stack. I would go with something like the following:
public MainPage()
{
InitializeComponent();
SomeFunction();
}
public void SomeFunction()
{
int id;
DownloadFromAPI("url to api", out id);
MessageBox.Show(id.ToString());
}
public void DownloadFromAPI(url, out int id)
{
//retrieve data...
// set id...
id = Int16.Parse(data);
}
Related
I am relatively new in C#.
I am trying to understand how the flowing bit of code is working.
public static int Method3()
{
//some code
If(Class1.Method1(int Variable1).Method2(Class3 Variable2))
{
//even more code
}
//some code
}
OK, now a bit of context.
This if-statement is in Method3 and Method3 is the Class Class1.
Method1 takes an Int value and returns NULL or an Class Class2.
Method2 takes a Class lets call it Class3 and it returns true or false.
So I understand for the if-statement to be valid the condition must return true or false.
Which will come from the Method2 from my understanding.
But what is Method1 doing here?
What happens with the output of Method1?
Does it have any influence to the condition?
I hope you guys can understand what I mean.
If not please ask.
It would be far easier to understand if you get an example with more meaninful names.
Warning: This code and the one in your question is vulnerable to NullReferenceException. If GetClient returns null, you will have an exception.
For example:
public static bool SellingExample1()
{
int clientId = 21;
// Possible NullReferenceException
if(Shop.GetClient(clientId).OwesMoney())
{
// Send warning email to sales manager
}
// Do selling logic
}
public static bool SellingExample2()
{
int clientId = 21;
Client clientToSell = Shop.GetClient(clientId);
if (clientToSell == null) return false; // Check to avoid NullReferenceException before calling methods on a null object.
bool clientOwesMoney = clientToSell.OwesMoney();
if(clientOwesMoney)
{
// Send warning email to sales manager
}
// Do selling logic
}
public class Shop
{
public static Client GetClient(int clientId)
{
// Look the database and return the client
}
}
public class Client
{
public int Id { get; set; }
public string Name { get; set; }
public bool OwesMoney()
{
// Return true if there are unpaid bills
}
}
A method doesn't take a class. It takes an instance of a class.
Think of a class as a description of a thing and an instance as a specific thing of that kind, e.g. Cat might be a class where "Tom the cat" might be an instance.
The picture is a little more complex because methods can be static meaning they belong with the class or not, meaning they belong with the instance. In the following, I'll assume you are dealing with static methods because the method in your example is static.
Because you are chaining method calls, I assume Method1 returns something (an object instance) you can call Method2 on.
Now let's look at how your code might be modified given that understanding:
public static int Method3()
{
//some code
int Variable1 = 42;
Class3 Variable2 = new Class3();
if(Class1.Method1(Variable1).Method2(Variable2))
{
//even more code
}
//some code
}
I refreshing myself on C# and C++ after having spent some time coding in other languages. I was wondering if I could do something like this:
class Customer
{
private long id;
public Customer()
{
id = 0;
}
public Customer(long initID)
{
id = initID;
}
public bool Add()
{
// TODO: Call web service to add a customer to the database
// ...
return true;
}
}
... the call
// Add Customer
// Two line way that is correct
Customer c = new Customer(1234);
bool isAdded = c.Add();
// One line way that isn't valid
bool isAdded = new Customer(1234).Add();
In other words, I don't really need the Customer object ... basically instantiate the object with a value and run the method and return the result of the method and dispose of the object ... all in a single statement.
Is there a way to do this as clean and as simple in one line in C# and/or C++?
Create a static class (you'd want to name it better though)
public static class CustomerOperations
{
public static bool Add(long initId)
{
// Do stuff using initId
return true;
}
}
Then call it so:
var isAdded = CustomerOperations.Add(1234);
Is there a way in C# to be able to refer to a a parameter by both an internal and external name (in Swift this is known as argument labels/parameters)?
What I mean is suppose I have the following:
public static class Sport
{
public static void Print(int id sportID)
{
Console.Out.WriteLine(sportID);
}
}
public static void main()
{
Sport.Print(id: 123);
}
Internally, I refer to the id as sportID, but externally, the parameter is known as id.
A little late to the game, but I was looking for something like this as well. It is not exactly what the OP is after, but I think it is close enough.
The parameter names that are set when you declare the methods can be called when calling the method.
Declaring the method:
static string[] Roster(int numberOfDaysOff, int daysOfStartOnDay) {
// Method logic with the set names
}
Calling the method:
Roster(numberOfDaysOff: daysOff,daysOfStartOnDay: startDay);
Hope this helps future readers :-)
public static void Print(int id)
{
int sportId = id;
Console.Out.WriteLine(sportID);
}
?
There's no language implicit way of aliasing the var that I'm aware of, but you can rename it by passing it to another, private function that calls it sportId, or you can assign it to a new var yourself in the function.
Not sure why you'd want to do this but here is one way:
class Parameters
{
private int _id;
public int ID
{
get { return _id;}
set { _id = value;}
}
public int SportID
{
get { return _id;}
set { _id = value;}
}
}
I have a public class that is is used to create a dll. It has a variable and a property. Let`s assume it looks like this:
public class Main
{
private int _someInt = 0;
public int SomeInt
{
get { return this._someInt; }
set
{
this._someInt = value;
if (this._someInt == 1)
{
_someInt = 0;
}
}
}
public int ExecuteMain()
{
OtherClass.DoSomething(this.SomeInt);
}
}
I also have another class, in a separate project in the OtherClass class, that has the static DoSomething method:
public static void DoSomething(int someInt)
{
someInt = 1;
}
My problem is that SomeInt property in the Main class is getting set to 1 by the DoSomething method of OtherClass, but this does not trigger the setter in the Main class' property. Am I doing something wrong?
What you are doing is passing SomeInt by value to the DoSomething method, which gets a copy of the int and just changes its local value.
You can:
Pass by ref: public static void DoSomething(ref int someInt)
Pass the Main class and change the value inside DoSomething:
public static void DoSomething(Mainclass main)
{main.SomeInt = 1}
There is no way of doing this,even if you pass the field by reference using ref keyword it's not gonna work because your property has a setter method not your field.You should be changing the value of your property, in order to execute the setter method and perform the validation.
You can do that,passing the current instance of your class instead of the field, for example:
public int ExecuteMain()
{
OtherClass.DoSomething(this); // just pass current instance using 'this'
}
public static void DoSomething(Main obj)
{
obj.SomeInt = 1;
}
If you want to have it invoke the setter logic, one option is to do something like this:
public static void DoSomething(Action<int> setSomeInt)
{
setSomeInt(1);
}
then call it like this:
public int ExecuteMain()
{
OtherClass.DoSomething(x => this.SomeInt = x);
}
The concept here is that what you're really giving the method is not a variable that can be set, but rather an action that can be performed. This is an important distinction, as setting a property is really a kind of action, which can have an arbitrarily complex implementation. This approach is a bit awkward in practice, though, so you'll want to think carefully about what you're really trying to do here and whether there's a better way to express the desired dependency.
Firstly I apologise for the oversimplification, but I have this issue which is driving me crazy. It should work - it's simple code, nothing fancy.......
I have this object
public class Stuff
{
private int intStuff;
private string strStuff;
public Stuff(int StuffID, string Stuff)
{
intStuff = StuffID;
strStuff = Stuff;
}
public int StuffID
{
get { return intStuff; }
set { intStuff = value; }
}
public string Stuff
{
get{return strStuff;}
set{strStuff=value;}
}
}
Which is used in this class:
public class StuffandThings
{
private List<Stuff> lstMyStuff;
public List<Stuff> StuffList
{
set { lstMyStuff = value; }
get { return lstMyStuff; }
}
public StuffandThings()
{
lstMyStuff = new List<Stuff>();
}
}
Which is declared as a static in Global.asax <<<< this may be important
public static StuffAndThings MyStuff;
protected void Application_Start(object sender, EventArgs e)
{
MyStuff = new StuffandThings();
}
And when I use it in code:
foreach (string strStuff in lstStuff)
{
objStuff = new Stuff(intStuff,strStuff);
Global.MyStuff.StuffList.Add(objStuff);
}
It compiles and I can run in debug (it's a WCF Web service), my variables (intStuff and lstStuff) are all valid.but when I click on Service.svc in the browser I get the following error.
CS1502: The best overloaded method match for 'System.Collections.Generic.List.Add(Stuff)' has some invalid arguments
I don't think I can see the wood for the trees with this one and the interwebs have been no help.
Aso, all my other objects and functions in the global object are fine - hashtables mostly, and my code ran until I tried to add this functionality. I would use a hashtable but I would need the key to not be unique;
Any Ideas, please?
Thanks
P
You should declare the type of objStuff inside the loop. Always declare variables inside the smallest scope you can:
Stuff objStuff = new Stuff(intStuff,strStuff);
Global.MyStuff.StuffList.Add(objStuff);
If this fails to compile because objStuff is already in use in the parent scope then find a new name - objStuff2 for example, then everything should work.
Where is objStuff declared in your code? You might be picking up the declaration of something else that also happens to be called objStuff but is actually unrelated.