Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am trying to calculate the total for a list in my C# program, I have gotten help from several people in my class and we can't seem to find the problem, my code is,
int totalB = 0;
Cards.ForEach(delegate(ConsoleApplication1.Program.CreditCard Balance)
{
totalB= totalB + Balance;
});
The error is this Error 1 Operator '+' cannot be applied to operands of type 'int' and 'ConsoleApplication1.Program.CreditCard'
Any help for this would be much appreciated as I have no idea and neither do the people that tried to help me with this issue
I'm guessing you have a class like:
partial class CreditCard
{
public int Balance {get; set;}
}
So following what you have, explicitly, you most likely intended:
int totalB = 0;
Cards.ForEach(delegate(ConsoleApplication1.Program.CreditCard card)
{
totalB = totalB + card.Balance;
});
This iterates over each item in your Cards collection, and adds the value of the Balance property to totalB. Note I have called the variable card in the delegate to further illustrate what is going on - the delegate will be called once for each item in the collection. Inside, you can pick out the Balance property and add it to totalB.
Note you can also do this in a number of other ways:
Using LINQ:
int totalB = Cards.Sum(card => card.Balance);
Using a lambda expression instead of an explicit delegate:
int totalB = 0;
Cards.Foreach(card => {totalB += card.Balance;});
Using a foreach loop:
int totalB = 0;
foreach(CreditCard card in Cards)
totalB += card.Balance;
(If you are not familiar with it, the x += y is the same as x = x + y.)
As far as getting sum of list is concerned. it is as simple as (assuming Cards is a list)
Cards.Sum(x=>x.YourPropertyToSum);
Your Error:
The error is this Error 1 Operator '+' cannot be applied to operands of type 'int' and 'ConsoleApplication1.Program.CreditCard'
you are trying to add an int with ConsoleApplication1.Program.CreditCard (what is this) which is obviously not a type that can be added to int. Hence the error you are getting.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
Newb to C# and OOP. My journey thus far has been to take code bases that I've inherited from former developers and either address issues, or add enhancements, whilst trying to understand said code bases' structures from front-to-back.
I'm having trouble fully grasping the concept around the parameters which follow the initial declaration of a method. Here's an example of a method I'm working with:
public List<Entity> ParseCsvFile(List<string> entries, string urlFile)
{
entries.RemoveAt(entries.Count - 1);
entries.RemoveAt(0);
List<Entity> entities = new List<Entity>();
foreach (string line in entries)
{
Entity entityManagement = new Entity();
string[] lineParts = line.Split('|');
entityManagement.Identifier = lineParts[0];
entityManagement.ProductId = 1234;
entityManagement.Category = "ABCDE";
entities.Add(entityManagement);
}
return entities;
}
The part after ParseCsvFile in parentheses: (List<string> entries, string urlFile)
Could someone explain what these are and what they do, perhaps with metaphors/analogies/real-world examples?
It might be easier to see their purpose if you look at a simpler function for example:
public int Add(int number1, int number2)
{
return number1 + number 2;
}
Above there is a function that adds two numbers together and returns the result. It is a set of instructions to follow. How can it follow the instructions if it doesn't know what numbers to use.
That's where calling the function comes in.
for example:
var result = Add(2, 5);
In this scenario result = 7.
2 is replacing number1 in the function and 5 is replacing number2.
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 needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am working on an id tester. I get error CS1061 every second.
This is my code:
Process[]roblox=Process.GetProcessesByName("RobloxPlayerBeta.exe");
Console.WriteLine("Id of RobloxPlayerBeta.exe is:", roblox.Id);
int id = roblox.Id;
Compiler Error CS1061 will give you more details on why you get this error. But in your question you haven't include most important part of error details.
roblox is array, if you need to get id of process then you need to get item in the array. items of array can be access via index
Process[]roblox=Process.GetProcessesByName("RobloxPlayerBeta.exe");
if(roblox!=null && roblox.Length >0)
{
Console.WriteLine("Id of RobloxPlayerBeta.exe is:", roblox[0].Id);
int id = roblox[0].Id;
}
You have an array of processes roblox, but try to access the Id property of the entire thing as opposed to well... a process. In order to fix this you must actually select the index you wish to use the Id of
Process[] roblox = Process.GetProcessesByName("RobloxPlayerBeta.exe");
if(roblox.GetLength(0) > 0) //Check that any processes exist with that name
{
int id = roblox[0].Id; //set ID first as to avoid accessing the array twice
Console.WriteLine("Id of RobloxPlayerBeta.exe is:" + id); //Write the line using the newly found id variable
}
else //If the process doesn't exist
{
Console.WriteLine("RobloxPlayerBeta.exe is not running"); //Output error of sorts
}
Also fixed here is your Console.WriteLine(), the way you're using it would require a parameter like this Console.WriteLine("Id of RobloxPlayerBeta.exe is:{0}", id); or use concatenation like I do in the example. You seem to have attempted a mixture of the two, which doesn't work
If you are having any issues with getting to grips with arrays, have a read of this article
To paraphrase it, regarding the issue you had, once you have an array, for example
string[] stringArray = new string[] {"hello", "hi"};
You can access its contained objects like so
string firstIndex = stringArray[0]; //for the first index
string secondIndex = stringArray[1]; //for the second index
If we were then to write this
Console.WriteLine(firstIndex + secondIndex);
It would output hellohi
As a side note, you are receiving error CS1061 specifically because you are trying to access a property of the array which does not exist
NB: An interesting one-liner, using -1 to indicate the process is not running
int id = Process.GetProcessesByName("RobloxPlayerBeta.exe")?[0].Id ?? -1;
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 6 years ago.
Improve this question
I have a small piece of code to refactor. Someone wrote cast in such style:
list.OrderBy(u => (int)u.Original).First();
Sometimes this code throw Invalid Cast Exceptions (field Original is of type object).
Example:
list[0].Orginal = 200,
list[1].Orginal = 85
Everything is Ok.
list[0].Orginal = 275452,
list[1].Orginal = 154754
Throws Exception
Anyone know why?
Since it sometimes throws the invalid cast exception, it means you sometimes have non-int types of instances in your list. You can avoid them before casting, but this is not really a good type of a design I guess.
I would do as I show below as a quick fix.
list.Where(u => u.Original is int).OrderBy(u => (int)u.Original).First();
Then I would go ahead and check what am I missing as following:
list.Where(u => !(u.Original is int)).ForEach(u => Console.WriteLine(u.Original.GetType()))
Then fix the list beforehand.
As others suggested you should avoid the unnecessary cast. In your class simply change the type of Orginal from object to int and you won't need the cast in the LINQ query.
The code compiles and runs with no problem.
https://dotnetfiddle.net/dadrYJ
These are not the Datatypes you are looking for
What you actually meant was
https://dotnetfiddle.net/ygJTyU
list[0].Orginal = 2147483647;
list[1].Orginal = 154754;
where n > 0
Given that. The bug is pretty clear.
Refactor:
var value = int.MaxValue + n;
list[0].Orginal = value;
Refactor:
int64 value = int.MaxValue + n;
list[0].Orginal = value;
Therefore:
public int Lambda_OrderBy(Foo u)
{
return (int) u.Orginal;
}
Refactor:
public int Lambda_OrderBy(Foo u)
{
int64 value = u.Orginal;
return (int) value; // FAIL!
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I want to compare the array element with number.
ArrayList arr_obj = new ArrayList();
double a=1;
arr_obj.Add(1);
arr_obj.Add(2);
for(i = 0; i < arr_obj.Count; i++)
{
if (arr_obj[i] == a)
{
Debug.Log("ext");
}
}
This code does not work. Any ideas?
Yo are comparing an object to a double which won't compile. You will either have to store doubles in the ArrayList (as below) or first cast the values to int and then to double Ie (double)(int)arr_obj[i] because you can only unbox to the exact same type as you boxed (in your case that's int)
If you wish to stick to an ArrayList, not recommended, change to
ArrayList arr_obj = new ArrayList();
double a=1.0;
arr_obj.Add(1.0);
arr_obj.Add(2.0);
for(i=0;i<arr_obj.Count;i++){
if ((double)arr_obj[i]==a) {
Debug.Log("ext");
}
}
or you could use a List<double>
var list = new List<double>{1.0,2.0};
var a=1.0;
for(i=0;i<list.Count;i++){
if (list[i]==a) {
Debug.Log("ext");
}
}
You can convert it with Convert.ToDouble(arr_obj[i])
You have to cast the ArrayList to double:
(double)arr_obj[i]
ArrayList can contain any type beacause it is a list of objects. So, if you are going to cast it like this, you need to be sure that each array list is of type double by only putting doubles in the array list, or check it before casting like:
if (arr_obj[i] is double)
{
if ((double)arr_obj[i] == a)
{
Console.WriteLine(arr_obj[i].ToString() + " is double");
}
}