Assign objects data into another object with out passing reference in c# - c#

public class ABC
{
public int x;
public int y;
}
ABC _prevABC;
ABC abc;
public void A()
{
_prevABC = new ABC();
_prevABC = abc;
abc.x = 10;
}
public void B()
{
abc = _prevABC;
}
In above methods I called A and then B , even then abc.x value is 10 which I updated in A.
So it seems even though I created new Object of ABC and assigning with = its just passing reference.
How to assign with out passing reference?

_prevABC = abc line is making you problem, you assign reference of abc to _prevABC.
If your class actually holds only some values like in example you gave you could use struct because it assigns values instead reference.
If you want to keep class then you could do something like this:
_prevABC = new ABC();
_prevABC.x = abc.x;

Related

How to pass a Setter to a constructor

given the following:
public class ClassA
{
private int val;
public int setter1 { set{ val = value * 100 }}
public int setter2 { set{ val = value * 200 }}
}
public class ClassB
{
public int setter;
public ClassB(int someSetter)
{
b = someSetter; // Obviously impossible, it's merely for demonstration purposes
}
}
Would it be possible to assign Getter/Setters to instances that belong to a different class?
So that when we create 2 instances:
B b1 = new B(setter1),
b2 = new B(setter2);
b1.setter = 1; // 'val' is equal to 100
b2.setter = 2; // 'val' is equal to 400
The reason I need this:
I have a bunch of instances that belong to the same class, and a local variable which I assign data to.
I don't know which instance I'm accessing, but I want to assign a Setter so that the value of the local variable changes.
I can easily achieve this differently, but I was wondering if passing Setters was possible.
Thx for reading!

I can't get value of base class field from child class object in c#

using System;
public class Program
{
public static void Main()
{
CloudCollectionHelper cloudHelper = new CloudCollectionHelper();
SlackHelper slackHelper = new SlackHelper();
cloudHelper.DatabaseID=12345;
Console.WriteLine(slackHelper.GetSlackPageTokens());
}
class CloudCollectionHelper
{
public long DatabaseID { get; set; }
}
class SlackHelper:CloudCollectionHelper
{
public long GetSlackPageTokens()
{
return DatabaseID;
}
}
}
current output: 0
Expected Output: 12345
I need output 12345 because DatabaseID from the cloudhelper so i need that databaseID in the slackhelper.
this is my c# online compiler: https://dotnetfiddle.net/QNQeEX
The child class does not get the assigned values from the base class. Becouse there can be mutliple instances from it. For example, if you have
...
CloudCollectionHelper cloudHelper1 = new CloudCollectionHelper();
CloudCollectionHelper cloudHelper2 = new CloudCollectionHelper();
cloudHelper1.DatabaseID = 1234;
cloudHelper2.DatabaseID = 6789;
Console.WriteLine(slackHelper.GetSlackPageTokens()); //It would not know, what value to use.
...
The best way would be assigning the value directly to the child class or using the static modifier.
Edit:
Best way if you need to take this value from the child class for whatever reason would be doing something like this:
...
CloudCollectionHelper cloudHelper = new CloudCollectionHelper();
cloudHelper.DatabaseID = 12345; //First assign the needed Value
SlackHelper slackHelper = new SlackHelper(cloudHelper); //then create a new instance from the child class
...
and add the constructor from the SlackHelper child class like this:
class SlackHelper:CloudCollectionHelper
{
public SlackHelper(CloudCollectionHelper cloudHelper)
{
this.DatabaseID = cloudHelper.DatabaseID;
}
... //Do everything else what this class needs here
}
If the Value from cloudHelper.DatabaseID can update during the runtime, you will need a event to update the child class. It still isn't the best way to do this, because the DatabaseID value is already public and can be accessed without the child class.
Edit 2:
Like I already told you in the comments, you could also avoid this problem with the static modifier. But this will effect every instance made from the CloudCollectionHelper class. As soons as you make it static, this will only hold 1 possible value for all instances.
(Please keep in your mind to use a comment if needed or best case, just avoid Magic numbers)
The property of your Object slackhelper has not been affected.
You don't need to create a CloudCollectionHelper Object.
SlackHelper slackHelper = new SlackHelper();
slackHelper.DatabaseID=12345;
Console.WriteLine(slackHelper.GetSlackPageTokens());
You should create this property inside the class to allow to read the Database ID
public long GetSlackPageTokens()
{
return base.DatabaseID;
}

Make variable point to another variable

I need to have an instance which is the pointer of another instance. Basically, I will have two instances called A and B created from the same class. whenever I will change an attribute of A instance the B instances attribute will be changed. Basically, the attributes will have the same address on the memory.
I just want to reach the same object with different variable names. Whenever one of them will be edited, the other one should be edited too.
How can I do that in Unity with c#?
I will have 2 instances with same type. Whenever one of them will be
edited, the other one should be edited too.
I just want to reach the same object with different variable names.
You can use properties to fake pointing to another variable. This is easily done with the get and set accessors.
Let's say that the main variable is named score:
public int score;
You can point to the score variable with two other variables:
public int scoreWithDifferentName1
{
get { return score; }
set { score = value; }
}
and
public int scoreWithDifferentName2
{
get { return score; }
set { score = value; }
}
Now, you can change the score variable or access it with those two property variables above:
scoreWithDifferentName1 = 0;
Debug.Log(scoreWithDifferentName1);
Or
scoreWithDifferentName2 = 3;
Debug.Log(scoreWithDifferentName2);
Another option is to use IntPtr but this is not necessary. The C# property feature is enough to give you what want. This works both for value and reference types.
This seems like a design question of how you want your classes to look like and what are their responsibilities. I'm not sure what is the purpose of the class that you're talking about but the obvious solution here is an attribute with a static modifier.
Adding a static attribute to your class will insure it will have the same value across all instances, i.e.:
public class ClassX
{
public static string staticVar = "This is a static string";
private string var1;
}
It sounds like you're describing the regular way reference types work in C#:
public class MyClass
{
public string Name {get;set;}
}
void Test()
{
var a = new MyClass();
a.Name = "Test";
var b = a;
Console.WriteLine(a.Name); // "Test"
Console.WriteLine(b.Name); // "Test"
b.Name = "MossTeMuerA";
Console.WriteLine(a.Name); // "MossTeMuerA"
Console.WriteLine(b.Name); // "MossTeMuerA"
Mutate(a);
Console.WriteLine(a.Name); // "John"
Console.WriteLine(b.Name); // "John"
}
void Mutate(MyClass myClass)
{
myClass.Name = "John";
}
Example 1
Note that if you want to modify which class instance the variable passed to a method points to, you need to use the ref keyword:
void Test()
{
var a = new MyClass();
a.Name = "Test";
var b = a;
Console.WriteLine(a.Name); // "Test"
Console.WriteLine(b.Name); // "Test"
Mutate(ref a);
Console.WriteLine(a.Name); // "John"
Console.WriteLine(b.Name); // "Test"
}
void Mutate(ref MyClass myClass)
{
myClass = new MyClass();
myClass.Name = "John";
}
Example 2
There is also another keyword, out, which allows a method to instantiate an object in the scope of the caller by passing in the variable you want to populate:
void Test()
{
MyClass a;
Instantiate(out a);
Console.WriteLine(a.Name); // "John"
}
void Instantiate(out MyClass myClass)
{
myClass = new MyClass();
myClass.Name = "John";
}
Example 3

How to add value to an array of object in C#

I am consuming a third party web service and I want to add value to match the service reference class, and i am not sure how to add value to the following:
in reference:
public partial class UserInfor: object, System.ComponentModel.INotifyPropertyChanged
{
private ABC[] listOfABCField;
public ABC[] ListOfABC
{
get {
return this.listOfABCField;
}
set {
this.listOfABCField = value;
this.RaisePropertyChanged("ListOfABC");
}
}
}
public partial class ABC : object, System.ComponentModel.INotifyPropertyChanged
{
private string ipField;
private string fristNameField;
private string lastNameField;
}
//////////////////////////////////////////////////////
in my service.asmx file have tried to put value as below:
in below code i got exception in line ABC[] abc=new ABC[0]; error code:(NullReferenceException)
UserInfor user = new UserInfor();
ABC[] abc=new ABC[0];
abc[0].firstName= "petter";
abc[0].lastName = "lee";
user.ListOfABC = abc[1];
i also tried
in below code i got exception in line user.ListOfABC[0] = abc; error code:(NullReferenceException)
UserInfor user = new UserInfor();
ABC abc=new ABC[0];
abc.firstName= "petter";
abc.lastName = "lee";
user.ListOfABC[0] = abc;
any idea how to add abc to user class ? thank you in advance
This'll probably be easier if you use a List<> instead of an array. Change the property:
private List<ABC> listOfABCField;
public List<ABC> ListOfABC
{
// etc.
}
Don't forget to initialize it in the class' constructor so it's not null:
public UserInfor()
{
listOfABCField = new List<ABC>();
}
Then you can just add an object to it, which doesn't need any of the array syntax you were trying to use:
UserInfor user = new UserInfor();
ABC abc = new ABC();
abc.firstName= "petter";
abc.lastName = "lee";
user.ListOfABC.Add(abc);
You are doing it wrong, first instantiate the array, if you know in advance how many items it would contain then specify that as well in the square brackets like:
ABC[] abc=new ABC[1]; // this array will contain 1 item maximum
now instantiate that item and then set values of properties :
abc[0] = new ABC(); // instantiating first item of array which is at 0th index
abc[0].firstName= "petter";
abc[0].lastName = "lee";
If you don't know how many item would come in it, then go with #David's suggestion of using List<T>

Passing an object to another class?

I've recently been looking into constructors, Im currently trying to pass a object to another class file, The way im doing it is like this:
class Program
{
static void Main(string[] args)
{
Class1 objPls = new Class1();
objPls.nameArray[0] = "jake";
objPls.nameArray[1] = "tom";
objPls.nameArray[2] = "mark";
objPls.nameArray[3] = "ryan";
Echodata form2 = new Echodata(objPls);
}
}
class Class1
{
public string[] nameArray = new string[3];
}
class Echodata
{
public Class1 newobject = new Class1();
public Echodata(Class1 temp)
{
this.newobject = temp;
}
// so now why cant i access newobject.namearray[0] for example?
}
Problem is i cant access the object to get into the array..
What methods of passing objects are there? I was told this is roughly a way to do it and have been experimenting for a while to no avail.
Not sure what it is you cannot do. For example your code with this modification works, or at least compiles.
class echodata
{
public Class1 newobject = new Class1();
public echodata(Class1 temp)
{
this.newobject = temp;
}
// so now why cant i access newobject.namearray[0] for example?
// What kind of access do you want?
public void method1()
{
newobject.nameArray[0] = "Jerry";
}
}
You have an issue where your code will throw an error when trying to set the "ryan" string on the fourth index of the array. You initially set the array to be of length 3.
In your EchoData class you can access the nameArray object without an issue but you must be accessing it within a method or in the constructor. You cannot be manipulating it's content outside of these.
Keep in mind that within your EchoData class you will not see the values you set inside of your Main method.
It's hard to tell since you haven't included a complete, compilable sample, and you haven't explained exactly what "can't access" means (do you get an error? what is it?)
However, my guess is that you are attempting to access the passed in objects fields from the class level based on your code.
ie, you are trying to do this:
class Echodata
{
public Class1 newobject; // you don't need to initialize this
public Echodata(Class1 temp)
{
this.newobject = temp;
}
newobject.newArray[0] = "Can't do this at the class level";
}
You can only access nameArray from within a member method.
class Echodata
{
public Class1 newobject; // you don't need to initialize this
public Echodata(Class1 temp)
{
this.newobject = temp;
}
public void DoSOmething() {
newobject.newArray[0] = "This works just fine";
}
}

Categories

Resources