Create an object ArrayList from a class - c#

I want to know if is possible in Visual Studio 2005 C++ to create an ArrayList of objects of a class.
I will have this class:
class var
{
int x;
int y;
}
In C# is something like this: ArrayList<var> list = new ArrayList<var>(); , but in C++ doesn't work.
I forgot to mention that the project is a Windows Form Application.

Have you tried std::vector<var> myVector or std::list<var> myList?

That should do the job:
#include <vector>
using std::vector;
class var
{
int x;
int y;
};
int main(void)
{
vector<var> myVec(10); // creates a vector of 10 elements of var objects
// ... other stuff
return 0;
}
But there are many more ways to put objects into a vector, e.g. create an empty vector and using vector::push_back(), etc. You should read the Standard libs' documentation for all the alternatives.

You can do this:
var myArray[50];
Which are 50 vars on the stack. You can also do this:
var* myArray = new var[50];
Which are 50 vars on the heap. Or you could just use a std::vector:
var myObject;
std::vector <var> myVector;
myVector.push_back(var);
Or, the last one that I usually use is:
std::vector <var*> myVector;
var* pVar = new var();
myVector.push_back(pVar);
There are way too many ways of doing it, these are just a few.

Related

List from C# to C++

in C# I had the following class:
public class PixelInfo
{
public DateTime CreatedTime;
public float x;
public float y;
}
with the following code I was able to save multiple pixels:
private readonly List<PixelInfo> _pixels = new List<PixelInfo>();
foreach...
{
_pixels.Add(new PixelInfo()
{
CreatedTime = DateTime.Now,
x = xx,
y = yy,
});
}
Now I want to do the same in C++ and I tried it the following way:
std::list<PixelInfo> _pixels = {};
_pixels.push_back(new PixelInfo()
{
...
});
but this gives me an error. How can I save a List of multiple pixels using the class properties?
First of all, a C# List is not the same as a C++ std::list. In C# a list is more like a C++ std::vector, and it's std::vector that should be the default container to use.
Secondly, in C++ you don't have to use new to create objects. In fact, new in C++ creates an object somewhere in memory and returns a pointer to it. The result of new PixelInfo() will have the type PixelInfo* which is quite different from PixelInfo.
And thirdly, you can't initialize members of classes or structures in C++ like you do in C#.
I recommend using the emplace_back function of std::vector to create and initialize the objects:
std::vector<PixelInfo> _pixels;
// ...
_pixels.emplace_back(some_date_and_time, x, y);

Declare static classes so that they can be stored within List

I am developing a software that takes realtime-data and extracts a number of features from that depending on user input. Each available feature consists of one method that takes an array of doubles and return the wanted feature, such as this one for the MeanAbsoluteValue:
public static class MeanAbsoluteValue{
public static double Calculate(double[] data){
return data.Sum(s => Math.Abs(s)) / data.Length;
}
}
Since each of the features only has the one Calculate method I was thinking of trying to rewrite them so that they can be collected and chosen from that Collection.
I have tried writing an Interface for them to use, but since they are static this was not allowed.
Is there a way of doing this? And if so, could you point me in the right direction?
You can create an array of delegates constructed from the Calculate methods of these classes, like this:
Func<double[],double>[] array = new Func<double[],double>[] {
MeanAbsoluteValue.Calculate
, MeanValue.Calculate
, Deviation.Calculate
// ...and so on
};
Here is a demo on ideone.
Store delegates to your functions in a dictionary, and look them up by name
var methods = new Dictionary<string, Func<double[], double>>();
methods.Add("MeanAbsoluteValue", MeanAbsoluteValue.Calculate);
...
public double DoFunc(string name, double [] args)
{
var func = methods[name];
return func(args);
}
Just have a collection of Func...
var list = new List<Func<double[], double>(MeanAbsoluteValue.Calculate, Average.Calculate)
var accum = 0;
foreach(var func in list)
{
accum += func(new [] {1,3,4,});
}

c# can i optimize this code?

I have this on a button:
private void Button_Click(object sender, RoutedEventArgs e)
{
string s = "x12y04";
//make new instance for MyMath class
MyMath dRet01 = new MyMath();
//use the doubleArrayXY (in MyMath class) to get doubble array back
double[] retD = dRet01.doubleArrayXY(s);
//use the calcResultFromDoubleArray (in MyMath class) to get result
MyMath dRet02 = new MyMath();
double result = dRet02.calcResultFromDoubleArray(retD[0], retD[1]);
//DEBUG!
/*
string TEST1 = Convert.ToString(returnedDouble[0]);
MessageBox.Show(TEST1);
string TEST2 = Convert.ToString(returnedDouble[1]);
MessageBox.Show(TEST2);
string TEST3 = Convert.ToString(result);
MessageBox.Show(TEST3);
*/
}
where the class "MyMath" is:
public double[] doubleArrayXY(string inputValue)
{
//in case there are upper case letters, set all to lower
string inpLow = inputValue.ToLower();
//split the string on the Y (so this tech should also work for x89232y329)
//so this will create res[0] that is x89232 and an res[1] that is 329
string[] res = inpLow.Split(new string[] { "y" }, StringSplitOptions.None);
//in the first string that looks like x89232, remove the x
string resx = res[0].Replace("x", null);
//now get the x value to a double
double x = double.Parse(resx);
//now get the y valye to a double
double y = double.Parse(res[1]);
//return in a double array the x and then the y (x=double[0] and y=double[1])
return new double[] {x,y};
}
public double calcResultFromDoubleArray(double one, double two)
{
return (one * two);
}
Now I know the part in the class that is "calcResultFromDoubleArray" is kind of useless at this point, but I want to make that do some extra stuff later on.
what I wonder about the most is in the main code where I make this new dRet10, and later on make dRet02.
I was thinking at first I could do something like this:
double result = dRet01.calcResultFromDoubleArray(retD[0], retD[1]);
So in that case I would not need to create a new instance of MyMath, but this does not work.
So I need to call a new instance for the class (like I did), or can I do this in a more elegant way?
I'm still kind of new to C#, so I'm trying to learn how to program in a nice and elegant way, besides just making it work.
Since your methods don't really use any other state information besides the parameters passed they probably should be static so you would not have to create any instances of your class at all:
double[] retD = MyMath.DoubleArrayXY(s);
double result = MyMath.CalcResultFromDoubleArray(retD[0], retD[1]);
If all of your methods in MyMath are static, declare the class itself static - just like the System.Math class, so you cannot create instances at all.
You could make your calcResultFromDoubleArray method static, and then call it via MyMath.calcResultFromDoubleArray(val1, val2)
In your code there is not really a point of creating an instance of MyMath class. You can make the methods static
public static double[] doubleArrayXY(string inputValue) { ... }
public static double calcResultFromDoubleArray(double one, double two) { ... }
and call them like so
double[] retD = MyMath.doubleArrayXY(s);
double result = MyMath.calcResultFromDoubleArray(retD[0], retD[1]);
If you make your methods static you can do the following in your main class:
double result = MyMath.calcResultFromDoubleArray(MyMath.doubleArrayXY(s));
And change calcResultFromDoubleArray to take the array rather than two values (as its title suggests).
FYI you can also chain String operations because they return Strings as such:
string[] res = inputValue.ToLower().Split(new string[] { "y" }, StringSplitOptions.None);
No need to create double x and double y. Change the last part of the method to:
return new double[] {double.Parse(resx), double.Parse(res[1]};
While changes such as these (there are more, there often are) will be minimal increases in performance, they will increase it a bit (the most from the static part - new is relatively expensive).
Most importantly though, they make the code more readable and elegant.
It looks to me like the two methods on MyMath could (or possibly should) both be static since they rely on nothing at all outside the method. Quite often this is the case with things like Maths libraries. It seems others have said this too though.
In addition you may be better off to create a class or struct to represent your X/Y. It may be that it isn't appropriate but if it represents a thing then you might want a class to represent that thing as well. See for example the Point and PointF classes. I'd suggest one of these but they don't have the same precision that you are using (and your X/Y may not be points so it might not be appropriate)
Also the line you said didn't work:
double result = dRet01.calcResultFromDoubleArray(retD[0], retD[1]);
This should have worked with the code as shown. What error were you getting on it? dRet01 exists and so it should have worked just as well as creating a new instance. The comments that it should be static are most applicable but if you are new to C# I thought it worth pointing this out so you don't build up any wrong ideas about what is and isn't possible. :)

How to skip optional parameters in C#?

Example:
public int foo(int x, int optionalY = 1, int optionalZ = 2) { ... }
I'd like to call it like this:
int returnVal = foo(5,,8);
In other words, I want to provide x and z, but I want to use the default for Y, optionalY = 1.
Visual Studio does not like the ,,
Please help.
If this is C# 4.0, you can use named arguments feature:
foo(x: 5, optionalZ: 8);
See this blog for more information.
In C# 4.0 you can name the arguments occurring after skipped defaults like this:
int returnVal = foo(5, optionalZ: 8);
This is called as named arguments. Several others languages provide this feature, and it's common form them to use the syntax foo(5, optionalZ=8) instead, which is useful to know when reading code in other languages.
Another dynamic way to supply parameters of your choise is to implement your method(s) in a class and supply named parameters to the class constructor. Why not even add calls to methods on same line of code as mentioned here : How to define named Parameters C#
var p = new PersonInfo { Name = "Peter", Age = 15 }.BuildPerson();
This is a late answer, but for the people who get into this.
One could also use Overloads,that uses the same name as the method/function, but with a different set of parameters.
ea
int SummAll (int a=0, int b=1, int c=2)
{return a+b+c;}
int SumAll (int a=0;int c=10) //skipping B
{return a+c; }
This pattern equals how with intellicense we can browse through variations of functions.

What is the need Indexers in C#

Today I've gone through what indexers are, but I am bit confused. Is there really a need for indexers? What are the advantages of using an indexer..... thanks in advance
I guess the simplest answer is to look at how you'd use (say) List<T> otherwise. Would you rather write:
string foo = list[10];
or
string foo = list.Get(10);
Likewise for dictionaries, would you rather use:
map["foo"] = "bar";
or
map.Put("foo", "bar");
?
Just like properties, there's no real need for them compared with just named methods following a convention... but they make code easier to understand, in my view - and that's one of the most important things a feature can do.
Indexers let you get a reference to an object in a collection without having to traverse the whole collections.
Say you have several thousands of objects, and you need the one before last. Instead of iterating over all of the items in the collection, you simply use the index of the object you want.
Indexers do no have to be integers, so you can use a string, for example, (though you can use any object, so long as the collection supports it) as an indexer - this lets you "name" objects in a collection for later retrieval, also quite useful.
I think zedo got closest to the real reason IMHO that they have added this feature. It's for convenience in the same way that we have properties.
The code is easer to type and easier to read, with a simple abstraction to help you understand.
For instance:
string[] array;
string value = array[0];
List<string> list;
string value = list[0]; //Abstracts the list lookup to a call similar to array.
Dictionary<string, int> map;
int value = map["KeyName"]; //Overloaded with string lookup.
Indexers allow you to reference your class in the same way as an array which is useful when creating a collection class, but giving a class array-like behavior can be useful in other situations as well, such as when dealing with a large file or abstracting a set of finite resources.
yes , they are very use of
you can use indexers to get the indexed object.
Taken from MSDN
Indexers are most frequently implemented in types whose primary purpose is to encapsulate an internal collection or array.
Full Story
for some reason, use indexer can let you create meaningful index to store or map your data. then you can get it from other side by the meaningful index.
using System;
/* Here is a simple program. I think this will help you to understand */
namespace Indexers
{
class Demo
{
int[] a = new int[10];
public int Lengths
{
get
{
return a.Length;
}
}
public int this[int index]
{
get
{
return a[index];
}
set
{
a[index] = value;
}
}
}
class Program
{
static void Main(string[] args)
{
Demo d = new Demo(); // Notice here, this is a simple object
//but you can use this like an array
for (int i = 0; i < d.Lengths; i++)
{
d[i] = i;
}
for (int i = 0; i < d.Lengths; i++)
{
Console.WriteLine(d[i]);
}
Console.ReadKey();
}
}
}
/*Output:
0
1
2
3
4
5
6
7
8
9
*/

Categories

Resources