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);
Related
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
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 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
So I have a formatting question. I have a Consumer Model that has once method that forms the consumer model data into a string. Each field has its own defined length:
public class ConsumerModel
{
public string ConsumerId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string GenerateConsumerString()
{
var request = FormatRequestField(ConsumerId, 12);
request += FormatRequestField(FirstName, 15);
request += FormatRequestField(LastName, 20);
return request;
}
}
The method FormatRequestField(string, int) takes the field and returns a string that has been edited/padded to be the length given by the integer. My question is, should the lengths of the fields be stored as private variables? I know this is the normal practice so you don't end up with "mystery" integers - but each integer is only used once. Given that in my actual code there are around 50 properties for this model, that seems like a lot of extra lines of code to store the field lengths as private variables.
I was just wondering what the best practice would be for this situation. Thanks for the help.
should the lengths of the fields be stored as private variables?
No, they should be stored as private constants. Variables are things that can change; that's why they're called variables, because they vary. Constants are things that don't change; that's why they're called constants, because they are constant.
I know this is the normal practice so you don't end up with "mystery" integers - but each integer is only used once.
So what?
The purpose of the named constant is not to deduplicate an expression; it's to make the code legible to future developers who read it.
Given that in my actual code there are around 50 properties for this model, that seems like a lot of extra lines of code to store the field lengths as private variables.
You have a belief that 50 lines of code is "a lot". Fifty lines of code is nothing. Fifty lines of code declaring constants is a few minutes work. Fifty lines of constant declarations that never change is literally the cheapest fifty lines of code you will write in your career; why are you hesitating?
I was just wondering what the best practice would be for this situation.
You already know what the best practice is: avoid magic numbers and make your code legible to future developers.
Besides magic values, readability is very important. Code is read is much more often that it is written, so whatever you can do to help readability, you should do it. For example, you can hide length in a class with constants:
public static class FieldWidth
{
public const int ConsumerId = 12;
public const int FirstName = 15;
public const int LastName = 20;
}
Read this:
var request = FormatRequestField(ConsumerId, 12);
And compare:
var request = FormatRequestField(ConsumerId, FieldWidth.ConsumerId);
Which line contains meaning without you having to go to FormatRequestField and checking what 12 stands for? Which one will be meaningful to you in a month when you forget this code?
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 am making a sort of statistical software that firstly needs to 'detect' the datatype of an array.
Firstly, X[,] is an array of sometype, can be all strings, all double, all ints or a combination of all.
Now, for every column X[] I need to know the datatype. Like:
If everything is 0 or 1, then Boolean (or binomial)
elseIf everything is integer, then integer
elseIf everything is double, then double
else: String
I need something like this in C#.
So it seems what you're trying to do here is find the "lowest common denominator" of types here. The most derived type that all of the items in the collection "are".
We'll start out with this helper method to get the entire type hierarchy of an object (including itself):
public static IEnumerable<Type> BaseClassHierarchy(object obj)
{
Type current = obj.GetType();
do
{
yield return current;
current = current.BaseType;
} while (current != null);
}
Now we can take a sequence of objects, map each to its hierarchy, intersect all of those sequences with each other, and then the first item of that result is the most derived type that is common to all of the other objects:
public static Type MostDerivedCommonType(IEnumerable<object> objects)
{
return objects.Select(o => BaseClassHierarchy(o))
.Aggregate((a,b)=> a.Intersect(b))
.First();
}
One simple idea is you can try to cast/parse as the different types and if that fails, move on to the next type. A very brief example of this is:
foreach (var element in myArray) {
double parsedDouble; int parsedInt;
var defaultValue = element.ToString();
if (Double.TryParse(defaultValue, out parsedDouble)) {
// you have something that can be used as a double (the value is in "parsedDouble")
} else if (Int32.TryParse(defaultValue, out parsedInt)){
// you have something that can be used as an integer (the value is in "parsedInt")
} else {
// you have something that can be used as an string (the value is in "defaultValue")
}
}
I believe that should probably get you started. Good luck!
Note
As other's have said - it is better to use strong types in C#. In most cases you can probably select a single type and use that rather than performing the checks above.
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 need the fastest algorithm in .NET C# to compare two large collections (200000 records in each collection). I need to validate each row of collection 1 with each row of collection 2 and return the row of collection 1 which has duplicate records in collection 2.
Please suggest a linq query or lookup table which ever is faster..The records are like A2368FG,AD5686,B678SD,C68AGFD,...
private bool CheckValidCode(string stdCode, List<COde> CodeMap, out int count)
{
bool bRetVal = true;
count = 1;
try
{
List<COde> tempCodeMap = new List<COde>();
for (int i = 0; i < CodeMap.Count; i++)
{
if (CodeMap[i].StandardCode == (stdCode))
{
tempCodeMap .Add(customerCodeMappings[i]);
if (CodeMap[i + 1].StandardCode == (stdCode))
{
tempCodeMap .Add(CodeMap[i + 1]);
}
break;
}
}
return tempCodeMap ;
}
}
Are they simple string objects in each? If so, you can use something like
Collection1.Intersect(collection2)
Which will return all record that exist in both collections.
Is that what you wanted? It is not clear from your question if you want to find records that exist in collection1 and multiple times in collection2. If that is what you want, you will need to dig deeper.
Methods like Intersect() etc. should help.
Don't use collections, use Set<T> classes (or convert your collections to sets).
Then you can call methods like Intersect(), it is just faster (but you trade of memory for speed)