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 9 years ago.
Improve this question
I've seen certain .NET properties only allow adding and removing elements from a list through the += and -= operators. How do I create a property of a class with that functionality?
If you are talking about Properties, there is no way how determine "syntax use" of your properties in following way:
Enable i += 1;
Disable i = i + 1;
You maybe mismatched it with "delegate and events" which uses syntax += for some operations. For more info about delegates and events you should look at http://msdn.microsoft.com/en-us/library/aa645739(v=vs.71).aspx for example.
EDIT: Last alternative I could think of is operator overloading but I haven't experience to refer about this specific situation so there is link with more info C# operator overload for `+=`? but I don't think so that this is exactly what are you looking for, because it will not put restriction on syntax usage of your properties
You can achieve a similiar effect by doing:
public class Test
{
private List<string> _myList;
public Test()
{
_myList = new List<string>();
}
public List<string> MyList
{
get { return _myList; }
}
public void ManipulateList()
{
_myList.Add("string 1");
_myList.Add("string 2");
}
}
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 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
Let's say we have a data object X and some "processor" objects/methods A, B, C and D. A(X) produces a new X with some additional data (the result of A processing). B(X) produces a new X with some other additional data. C(X) also produces a new X with some additional data but it requires that A has already been ran against X.
So: A(X).B(X).C(X).D(X) should run properly. B(X).D(X).A(X).C(X) should also run properly. B(X).C(X).A(X).D(X) should fail (because C requires the info A produces).
Is this possible to implement in C# so that the order constraints are enforced in compile time? If not, is there a design pattern or some common strategy of how this should be implemented? There can be many processors and many constraints, what I'd like to avoid is having to declare a factorial number of types to keep track of whether a processor has been ran or not.
You can use inheritance, combined with generic constraints:
class Data {
}
class ExtendedData : Data {
}
static class Pipeline {
public static ExtendedData A<T>(this T value) where T : Data {
if (value is ExtendedData extended) {
return extended;
}
else {
return new ExtendedData():
}
}
public static T B<T>(this T value) where T : Data {
return value;
}
public static ExtendedData C(this ExtendedData value) {
return value;
}
}
These variants will work:
new Data().A().B().C();
new Data().B().A().C();
new Data().A().C().B();
This variant will be rejected by the compiler:
new Data().B().C().A();
C() will expect an ExtendedData, while B() will only deliver Data.
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 7 years ago.
Improve this question
It's probably a stupid question, but anyway.
My problem is that I can't pass uninitialized array, but I don't know if my array need to hold 5 or 30000 elements, eg. so it will be a waist of memory to initialize big array.
Should I use List<T> instead, or?
I've noticed people tend to return array instead of list, which is mutable, and therefore much more convenient, so there must be a performance issue with lists. Is that so?
make it into an 'out' parameter and all should be well:
private void x()
{
string sTestFile = "this is a test";
string[] TestFileWords;
FixConcatString(sTestFile, out TestFileWords);
}
private void FixConcatString(string splayfile, **out** string[] sWordArray)
{
char[] charSeparators = new char[] { '-' };
splayfile = splayfile.ToLower();
splayfile = splayfile.Replace(#"\", " ");
sWordArray = splayfile.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries);
}
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);