multiplication in C# basic program [closed] - c#

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 1 year ago.
Improve this question
In the Main function, declare three integer variables (name them arbitrarily) and initialize these variables with values (ideally different). Write a program that computes the following arithmetic expression: Multiply the values of the last two variables and subtract the value of the first variable from the obtained result. Write the arithmetic expression and its result on the screen in a suitable way.
using System;
namespace ConsoleApp4
{
class Program
{
static void Main(string[] args)
{
int prvni = 10;
int druha = 20;
int treti = 30;
int vysledek = (treti * druha) - prvni;
Console.WriteLine("Výsledek: {vysledek}");
}
}
}

String-interpolation in that way requires a $ (dollar-sign) before the string to specify that you are doing interpolation, so: Console.WriteLine($"Výsledek: {vysledek}");
For more examples on string interpolation: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated
An alternative solution could be to simply concatenate the variable to the string: Console.WriteLine("Výsledek: " + vysledek);

You need to print the varable correctly.
Console.WriteLine("the answer {0}", vysledek);
Take care,
Ori

Related

Parameters in parentheses after a method name: what are they and what do they do? [closed]

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.

Accessing a property through reflection returns a different value [closed]

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; }
}

Initialize int variable to minus one in C# [closed]

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

Why can't i convert from Fahrenheit to Celsius? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
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.
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.
Improve this question
My C# code keeps returnng me a wrong conversion result. As far as i know, the conversion formula is correct, but it keeps displaying wrong results.
e.g: 70°F gives me 12,777777 °C. Can you check my code out ?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Temperature
{
class Program
{
class Temperature
{
public double temp;
public void Convert(double value)
{
double tEmp;
tEmp = (value - 32) / 1.8;
Console.WriteLine("The temperature in °C is :" + tEmp);
Console.ReadKey();
}
}
static void Main(string[] args)
{
double f;
Temperature c = new Temperature();
f = Console.Read();
c.Convert(f);
}
}
}
your problem is
f = Console.Read();
It just reads the first character, not your entire line of input. Try
f = Convert.ToDouble(Console.ReadLine());
Here's a good answer on the difference between Console.Read vs. Console.ReadLine()
Console.Read() returns the ordinal value of the next character in the input stream.
The first character in your input stream is '7' which has an ordinal value of 0x0037. Represented as decimal this is 55 and (55-32)/1.8 is 12.7777.
You should be using Console.ReadLine() rather than Console.Read().

C# Printing variables using an "EXEC" Command [closed]

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
In python to print a list of 11 Variables i would do so using "Exec". There is a list of 11 Items, this code prints them all.
for count in range(1,11):
question = ("print " + "question" + str(count))
exec question
How would I do something similar in C# ?
(Without the use of lists)
Here's what i have so far
string line;
for (int i = 1; i < 200; i++)
{
line = ("Console.WriteLine(scene1_f"+i);
// Execute "line"
}
Thanks.
I think it would be wise if you read a few things on the c# language while you are trying out stuff. At the same time, it would be wise if I looked up some Python tutorials before attempting to answer such questions.
Although c# supports dynamic types and expressions, it is mostly used to create "strongly typed" constructs. For the example you provided I believe there are no easy / simple direct translations.
Your "scene1_f1" through "scene1_f200" variables would likely be instances of some c# type like a Scene class, that has some properties and methods that operate on the object instance.
If you have multiple Scene object that you want to perform the same type of operation on (like printing them to the console as in your example), it is generally considered good practice to group them in some manner, such as adding them to a List or storing them in an Array.
To illustrate what I mean I have added a hypothetical example:
public class Scene
{
public Scene(string name)
{
Name = name;
}
public string Name { get; set; }
// ... more properties
public void Draw()
{
// logic for drawing
}
// ... more methods.
public override string ToString()
{
// here return what you would want to have as
// a string representation of a Scene object.
return "Scene " + Name;
}
}
// in a different part of your code, create and add the Scene objects
var scenesList = new List<Scene>();
scenesList.Add(new Scene("Some scene name"));
// add more
// Now you can print them to the console like this:
foreach (var scene in scenesList)
Console.WriteLine(scene);

Categories