How to fill a variable in class in array of classes? - c#

I have a class with just one variable
public class C
{
int i;
}
And in another project file I create an array of classes
C[] classes = new C[100000];
So what i need to do to set some random value to the "i" variable in each class?

First you need to make C.i accessible. One way is to make C.i a public property. While you’re at it, public fields should be pascal cased and all identifiers should have meaningful names.
When naming public members of types, such as fields, properties, events, methods, and local functions, use pascal casing.
public class Foo {
public int Bar { get; set; }
}
Then you'd use System.Random. Instantiate it once and call Random.Next each time you want a random number.
using System;
var rand = new Random();
// int anyPositiveInt = rand.Next();
// int positiveIntLessThanFifteen = rand.Next(15);
// int intFromOneToFour = rand.Next(1, 5);
Finally, following the example in Creating N objects and adding them to a list, use System.Linq's Enumerable.Range, Enumerable.Select, and Enumerable.ToArray as follows:
Foo[] classes = Enumerable
.Range(0, 100000)
.Select(_ => new Foo { Bar = rand.Next() })
.ToArray();

If the requirement is to use a private field then I recant the earlier advice to make it a public property - properties might not have been taught yet
static void Main()
{
var r = new Random();
var maxValueOfI = 100;
var minValueOfI = -20;
var csArr = new C[100000];
for (var julius = 0; julius < csArr.Length; julius++) {
var brutus = r.Next(minValueOfI, maxValueOfI+1);
csArr[julius] = new C(brutus);
}
}
public class C
{
private int _i;
public C(int i){
_i = i;
}
}
So, what's going on here?
The main addition is a constructor to C. A constructor is a special method that is called by C# when a new object is constructed. Every class has one even if you can't see it (the compiler provides one if you don't). Constructors are methods that are intended to ensure the class is fully set up and ready to use. Because it's inside the class it has full access to all the data fields of the class:
public C(int i){
_i = i;
}
This constructor takes an int, and sets the private field _i to the value of the passed in number. It's quite common to use this naming pattern for fields (prefix with underscore) and it helps avoid a name collision with the arguments to the method (in this case called i). If they had both been called i the class one would have to be prefixed with this. and it's (IMHO) more clutter
This line of code calls the constructor:
csArr[julius] = new C(brutus);
We've previously calculated a random number between -30 and 100 (inclusive both ends) and stashed it in a variable called brutus. This number is passed to the constructor, which is called when we say new C. The resulting fully constructed C instance is stored in one of the array slots

try this
static void Main()
{
Random rand = new Random();
var max=100000;
C[] array = new C[max];
for (var i=0; i <max; i++)
array[i] = new C { Num = rand.Next(0, max)};
// or using a constructor
array[i] = new C (rand.Next(0, max));
}
public class C
{
public int Num {get; set;}
public C (int num)
{
Num=num;
}
public C (){}
}

First of all, in your current code i is a private field. Let's add a constructor to set this field:
public class C {
int i;
public C(int value) {
i = value;
}
}
Then you can try using Linq:
using System.Linq;
...
Random rand = new Random();
...
C[] classes = Enumerable
.Range(0, 100000)
.Select(i => new C(rand.Next(0, 100))) //TODO: Put the right range here
.ToArray();

Related

Using a method made in a parent class in a child class c#

I have two classes:
class ClassOne
{
Stack<int> s = new Stack<int>();
public Stack<int> MakeStack()
{
for (int i = 0; i < 10; i++)
{
s.Push(i);
}
return s;
}
}
class ClassTwo:ClassOne
{
Stack<int> st = MakeStack();
int[] array = new int[2];
private int[] GetFirstTwo()
{
for (int i = 0; i < 1; i++)
{
array[i] = st.Pop();
}
return array;
}
}
but when I am trying to use MakeStack in the child class it gives the error "A field initalizer cannot reference the non-static field, method, or property 'ClassOne.MakeStack'.
I know one fix would be to do everything inside the parent class and make it abstract for when I need to override things inside different child classes, but was hoping there is a way to do what I need without all that as I couldnt find anything helpful when looking into it.
Use the constructor:
class ClassTwo : ClassOne
{
Stack<int> st;
ClassTwo()
{
st = MakeStack();
}
// ...
}
For the why look for example here: Understanding C# field initialization requirements

How do I add an integer variable to an integer value in a class?

I have a public variable stored in a class that is accessible through a constructor and would like to know how I can take an integer value returned by a number generator and add it to the variable's int value. Ex:
the class container
public class Values
{
public static Values myValues = new Values();
public int myNumber = 5;
}
generator in separate class/method
public static Values myValues = new Values();
public static void theMethod()
{
Random randNum = new Random();
int numGain;
numGain = randNum.Next(1, 6);
}
I basically want the generated value of numGain to add to the value of myNumber.
It sounds as if you want your Values class to keep track of the sum of numbers, is that correct? If so, it might be better to do something like this:
public class Values
{
private int myNumber = 0; // Default value set to 0
public int Add(int input){
myNumber += input; // Increases myNumber by input
return myNumber; // Return the new sum if you want to.
}
// If you need the number without changing it:
public int GetValue() { return myNumber; }
}
Using that:
public static Values myValues = new Values();
public static void TheMethod()
{
Random randNum = new Random();
int numGain = randNum.Next(1, 6);
// Now add the number to the instance of Values created above:
myValues.Add(numGain);
}

Accessing properties of elements in a collection to create new collections

Is there any way to define a table as a collection of rows, and automatically populate properties (columns) on the table according to the properties of the rows?
For example:
public class Foobar {
public int TheNumber;
public string TheString;
}
public class SomeFoobars : List<Foobar> {
public List<int> TheNumber {
get { return Select(foo => foo.TheNumber); }
set { for (int i = 0; i < Count; i++) { this[i].TheNumber = value[i]; }
}
public List<int> TheString {
get { return Select(foo => foo.TheString ); }
set { for (int i = 0; i < Count; i++) { this[i].TheString = value[i]; }
}
}
// So I can now do things like:
SomeFoobars myFoobars = ReturnsListOfFoobar();
MethodThatTakesListOfInt( myFoobars.TheNumbers );
myFoobars.TheString = SomeMethodThatReturnsListOfString();
Creating the collection class implementation isn't so bad if you only have to do it once, but I would like to have this functionality for any type of row and not have to write the collection properties over and over. These property methods are essentially identical, other than the reference to the specific property on the contained class (i.e. TheNumber or TheString in the example above).
Is there any way to accomplish this? Perhaps using reflection?
I would suggest you to go back and revise your design. As you may realize now, it is causing a lot of trouble to you.
With that being said if you still decide to keep the current kits, you can remove the properties on SomeFoobars and still do the same in this way :
MethodThatTakesListOfInt(
myFoobars
.Select(f => f.TheNumber)
.ToList());
SomeMethodThatReturnsListOfString()
.Select((s,i) => new { Index = i, String = s })
.ToList()
.ForEach(x => myFoobars[x.Index].TheString = x.String);

C# pass by ref different types of object that have the same properties inside and populate them without interface

How to pass by ref different types of objects that have the same properties inside and populate them without interface.
In my app there are totally different types which have some properties in common.
Let's say this properties are double arrays.
double[] samples;
Now I have to populate these samples for 20 objects.
I don't have any access to the class definition of this object, so I can't make interface, or make them inherit from a base class.
How can use one method which I call and this method to populate all my properties.
I want to have one method like this:
private static void FillSamples(ref WhoKnowsWhat dataType, MyObject theSamples)
{
for (int i = 0; i < sampleCount; i++)
{
dataType.SampleLength[i] = MyObject.X[i];
dataType.SampleValue[i] = MyObject.y[i];
}
}
And call this with totally different types.
FillSamples(ref BigStruct.OneTypeMine, theSamples);
FillSamples(ref BigStruct.AnotherTypeMine, theSamples);
FillSamples(ref BigStruct.HisType12345, theSamples);
Then the big struct should have these samples filled in the end.
Is there a way in C#?
Thanks!
You can use the dynamic keyword:
private static void FillSamples(dynamic dataType, MyObject theSamples)
{
for (int i = 0; i < sampleCount; i++)
{
dataType.SampleLength[i] = MyObject.X[i];
dataType.SampleValue[i] = MyObject.y[i];
}
}
Edit:
Using reflection (if you don't use .Net 4.0 or higher):
private static void FillSamples(object dataType, MyObject theSamples)
{
Type t = dataType.GetType();
var px = t.GetProperty("SampleLength");
var py = t.GetProperty("SampleValue");
for (int i = 0; i < sampleCount; i++)
{
px.SetValue(dataType, MyObject.X[i], null);
py.SetValue(dataType, MyObject.Y[i], null);
}
}
Don't know if it helps you any, but you can use reflection to find out what properties (and fields, methods etc.) an object supports at runtime. Check out http://www.csharp-examples.net/reflection-property-names/ for example, if you're interested in learning more.
You can use dynamic objects. You should be careful when targeting fields of a dynamic object since they cannot be checked at compile time. See my example below:
[TestFixture]
public class DynamicObjects
{
[Test]
public void Dynamic_Call()
{
dynamic obj1 = new Apple();
obj1.Weight = 100;
obj1.Color = "Red";
dynamic obj2 = new Orange();
obj2.Weight = 200;
obj2.Width = 10;
Assert.IsTrue(obj1.Weight < obj2.Weight);
}
}
public class Apple
{
public int Weight { get; set; }
public string Color { get; set; }
}
public class Orange
{
public int Weight { get; set; }
public int Width { get; set; }
}

The Field Is Never Assigned To And Will Always Have Its Default Value null

I currently have 2 bool arrays in a class file as defined by
public static bool[] bArray;
public static bool[] randomRemove;
And I fill bArray like this
public static void fillArray()
{
for (int x = 0; x < 54; x++)
{
bArray[x] = false;
}
}
And I fill randomRemove like this
for (int i = 0; i < sizeOfArray; i++)
{
randomRemove[i] = false;
}
Where sizeOfArray is the length of string array that I use.
I have two warnings for each bool array that says they are never assigned to and will always have its default value of null but I clearly have code that assigns them. Whenever I try to click a button that utilizes the arrays I get a run time error. Is there any reason this is happening?
You need to call
bArray = new bool[sizeOfArray];
somewhere in your code before you use them. Also, bool arrays default to all falses.
You are not instantiating your arrays - see http://msdn.microsoft.com/en-us/library/aa288453(v=vs.71).aspx for more info.
e.g.
public static bool[] bArray = new bool[sizeOfArray];
public static bool[] randomRemove = new bool[sizeOfArray];
You did not create instances of the arrays. Try
public static bool[] bArray = new bool[54]();
public static bool[] randomRemove = new bool[sizeofarray]();
instead.
You need to initialize the arrays in your constructor or where it makes sense.
public class MyClass
{
public static bool[] bArray;
static MyClass()
{
bArray = new bool[54];
}
}
In your code you are only assigning the items in the array which will give you a NullReferenceException because your array = null. You need to initialize the array.

Categories