Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I want to know how to use a global variable - which I already instantiated it as a public integer type - in a method later.
Here's my code so far:
public int money = 500000;
//other variables
//...some code in between
public static void UpdateResources (int cost, int airRate, int waterRate, int foodRate, int energyRate, int maintenanceRate, int happinessRate)
{
// \/ Problem here
if (money < cost)
{
//uncheck box
}
else
{
//implement input variables with other external variables
}
}
Remove "static" keyword from your method, static method cannot access instance variables. Static method is something belong to the type itself, while your instance variable is not. another option is to put the "money" as static, but than all your instances going to use the same "money" which is probably not what you aiming for.
public void updateResources (int cost, int airRate, int waterRate, int foodRate, int energyRate, int maintenanceRate, int happinessRate)
{
// v- No more Problem here :)
if (money < cost)
{
//uncheck box
}
else
{
//implement input variables with other external variables
}
}
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I am trying to sort two objects by one of their properties (.Transaction.topLeftX, an integer) using the following code to create a comparer to use in a Sort method:
public class RespComp : IComparer<Kairos.Net.RecognizeImage>
{
public Kairos.Net.RecognizeImage Compare(Kairos.Net.RecognizeImage x, Kairos.Net.RecognizeImage y)
{
if (x.Transaction.topLeftX.CompareTo(y.Transaction.topLeftX) <= 0) return x;
else return y;
}
}
However, I get the error message Error CS0738 'RecogniseFacesKairos.RespComp' does not implement interface member 'IComparer.Compare(RecognizeImage, RecognizeImage)'. 'RecogniseFacesKairos.RespComp.Compare(RecognizeImage, RecognizeImage)' cannot implement 'IComparer.Compare(RecognizeImage, RecognizeImage)' because it does not have the matching return type of 'int'.
Does the comparer used in the Sort method need to have return type int?
The IComparer<T> interface is supposed to implement a method that returns an int comparison. -1 for less than, 0 for equal and 1 for greater than.
Look at your code, if you're just comparing the top left, you can probably just do the following:
public int Compare(FooImage x, FooImage y) {
return x.Transaction.topLeftX.CompareTo(y.Transaction.topLeftX);
}
The desired outcome of sorting objects by one of their parameters was achieved by the following code:
...
Kairos.Net.KairosClient client = new Kairos.Net.KairosClient();
client.ApplicationID = appId;
client.ApplicationKey = appKey;
Kairos.Net.RecognizeResponse resp = client.Recognize(...);
RespComp SortImages = new RespComp();
resp.Images.Sort(SortImages);
...
public class RespComp : IComparer<Kairos.Net.RecognizeImage>
{
public int Compare(Kairos.Net.RecognizeImage x, Kairos.Net.RecognizeImage y)
{
return x.Transaction.topLeftX.CompareTo(y.Transaction.topLeftX);
}
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I have a 2 lists with 2 other objects. I want to use one function to add both different object to both different lists.
I do the following:
My lists:
List<Kelner> kelnerzy = new List<Kelner>();
List<Kasjer> kasjerzy = new List<Kasjer>();
My Kasjer class, the second is similar
class Kasjer
{
public Kasjer()
{
Free = true;
}
public bool Free { get; set; }
}
My function, where ilosc=3:
private static void Dodaj_do_list<T>(List<T> objects, int ilosc) where T : new()
{
for (int i = 0; i < ilosc; i++)
{
objects.Add(new T());
}
}
And then I just called function and added 2 objects normally like this:
Dodaj_do_list(kasjerzy, 3);
kasjerzy.Add(new Kasjer());
kasjerzy.Add(new Kasjer());
Display function:
for (int i = 0; i < kasjerzy.Count; i++)
{
Console.WriteLine(kasjerzy[i].Free);
}
I expect the output like this:
True
True
True
True
True
But the actual output is:
False
False
False
True
True
How can I fix it?
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
Ok, as my original question seemed a bit ambiguous because I was asking for a general question about the C# language, but showing part of a particular example where I was having a problem with it, I'm going to try to rewrite so that it is clearer that my question is about the C# language, not about my particular problem.
I currently have a property (several, in fact) of a class, that return a different value depending on whether you access them directly by code, or using reflection. This is what happens when I access the property using the immediate console of VS:
> SelectedLine.QtyOutstanding
0
> var prop = SelectedLine.GetType().GetProperty("QtyOutstanding")
> prop.GetValue(SelectedLine)
8
Regardless of how the property is defined, what is the difference, in C#, between both ways of accessing the property?
Shouldn't they both run exactly the same code in the setter/getter, if there is one?
(Considering that GetType() returns the same type as the variable is declared as)
I found a way to produce this, maybe your case looks like that?
If your SelectedLine is accessible via interface, and your class has an explicite implementation of that, but also has a public property with the same name, this could lead to different results.
Example
class Program
{
static void Main(string[] args)
{
var SelectedLine = (ILine)new Line(8);
Console.WriteLine(SelectedLine.QtyOutstanding); // 0
var prop = SelectedLine.GetType().GetProperty("QtyOutstanding");
Console.WriteLine(prop.GetValue(SelectedLine)); // 8
Console.ReadLine();
}
}
class Line : ILine
{
public Line(int qtyOutstanding)
{
QtyOutstanding = qtyOutstanding;
}
public int QtyOutstanding { get; }
int ILine.QtyOutstanding
{
get
{
return 0;
}
}
}
interface ILine
{
int QtyOutstanding { get; }
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I've come across some code where the variables are initialized to minus one. That's in some old code, is there any reason behind that? Because as far as I know all value types are initialized to zero.
I've tested the code and it doesn't change anything to leave the int variable uninitialized or with minus one, the result is the same.
Would you enlighten me?
class Program
{
static void Main()
{
SampleDelegate del = new SampleDelegate(SampleMethodOne);
del += SampleMethodTwo;
int Number = -1; //or -> int Number;
int returnedValue = del(out Number);
Console.WriteLine("returnedValue = {0}", returnedValue);
Console.ReadLine();
}
public static int SampleMethodOne(out int Number)
{
return Number = 1;
}
public static int SampleMethodTwo(out int Number)
{
return Number = 3;
}
}
public delegate int SampleDelegate(out int Number);
/returns 2
TL;DR: it depends, maybe there is no answer
Possible answer:
Initializing variable is better. you never know how it can be used in some later functions where having an unexpected value may be dangerous (when the code is optimized, you cannot be sure of the default value if not initialized).
In some case, an int may be used for some compatibility reason in the API when you just need an uint. In such a case, initializing to a negative value may be an easy way to detect an unset/invalid value.
No real reason, just an habit from the developer. I agree with comments, ask him if possible
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
For example:
public class Test
{
private string _s;
public Test()
{
var s = "hello";
_s = s;
}
public void Foo()
{
var s = _s;
// Use s for some reason.
}
}
Should I use _s directly for my needs or store _s into another variable that point to it? What if there were a property instead of the private field?
First, "encapsulate" is not at all the word for what you're doing. You're talking about making a copy. In programming, to "encapsulate" means to hide the field and make everybody access it via code of some kind. In C# that almost always means a property (which is really just method calls disguised by syntactic sugar). In other languages it might be explicit get and set methods.
So. Should you make a copy?
Yes:
private int _from = 9;
public void f(int to)
{
for (int i = _from; i < to; ++i)
{
// stuff
}
}
No:
public f2()
{
Console.WriteLine("from is {0}", _from);
}
If you're going to be changing the value as you use it, but you don't want the private field to be changed, make a local copy and change that.
But beware: Value types such as int behave very, very differently than mutable reference types such as SqlConnection (see below).
If you won't be changing it, don't waste your time. In fact, if the field is a reference type and you create a local reference to it, somebody maintaining your code ages hence may mistake it for a local object and wrongly assume that changes to it won't have class-wide effects.
private SqlConnection _conn = null;
public MyClass()
{
_conn = new SqlConnection();
}
public void f3()
{
var c = _conn;
// 150 lines of stuff
// OK, I guess we're done with it now!
c.Dispose();
c = null;
// Now _conn is not null, yet the next call to f3() will find it unexpectedly
// in an invalid state. You really don't want that.
}
Where did you get this idea from?
I see no reason to proxy the private field with a local variable. Most of the time, that field will be of a reference type (i.e., more or less, a class), so using a local variable only means one more reference to that object.
It could actually be harmful (anyway, doing unintended things) if you did that with a value-type field (an int, for example). You would act on the local variable, which is fine as long as you read it; but on write the field would not be changed.