Check from which Class the object has been created - c#

I was searching for a common question but couldn't find any solution even after googling. Maybe I am searching wrong?
Is it possible to know from which class the object has been created?
For Example: In Visual Basic Code:
I have a class,
Public Class dummyA
End Class
I have another class,
Public Class dummyMain
Dim dmmA As New dummyA
End Class
Can I check in dummyA, if the object has been created from dummyMain?
Answer with c# or VB.Net would be great. Thanks.

Easiest way is to have an overloaded constructor and pass the owner into it.
public class DummyA
{
public DummyA(object owner)
{
var createdByDummyMain = owner is DummyMain;
}
}
and then do
public class DummyMain
{
public DummyMain()
{
var dmmA = new DummyA(this);
}
}
There is also this but it won't give you exactly what you want. There are other proposals too that deal with StackFrame but it isn't reliable due to JIT optimizations.

Related

C# Give an constructor internal value

I am trying to give a class an object which don’t have control over it. That mean if the main class change the object, the class I’ve created have also the changes.
Example:
class main
{
private string test;
public main()
{
var Test = new Test(test);
}
}
If I change now the string “test” the object Test should also see the change string. Is that possible?
It is possible to do if you instead of string use a specially crafted class:
public class SharedData
{
public string Test {get;set;}
}
Then if you have an object of type SharedData instead of string, they will share the value. Strings are immutable in C#, so you wont' have the same string reference in both classes.
class main
{
private SharedData test = new ShareData();
public main()
{
var Test = new Test(test);
}
}
P.S. It's a different question whether this is a good design or not. It's hard to answer based on the examples you have provided. I would avoid such design if possible and rather pass string as parameter where you need it to have less state. But as always it depends and there can be cases where what you do is beneficial, but you can consider changing the design to make it easier.

sending instance of the current class to another as a parameter

I am looking for this Java code's equivalent in C#
public class MainClass {
public MainClass() {
OtherClass o = new OtherClass(this); //I am looking for "this" keyword to send the instance
}
public void someMethod() {
}
}
public class OtherClass {
public OtherClass(MainClass m) { //and this receiver method
m.someMethod();
}
}
I think there should be a way in C# to sent the current class as a parameter so that I can call the someMethod() in MainClass from OtherClass ?
How can I do that in C#?
Thanks for help..
I am looking for this Java code's equivalent in C#
Well, no equivalency needed. Your code is already a valid C# code without any modification. Here is a demo.
Note: I would be very worried about the circular reference in your code, but I'm sure it was just a simple sample and you wouldn't actually implement code like that.
Important Note: Just to be clear, you are not sending the "class". That's just not possible. You are sending an instance of the class. Maybe that's what you meant, but just so nobody reads it and get confused.

Access Parent/Owning class variable from composed class?

Forgive me because I know my wording is terrible. I'll just give an example.
public class MainClass{
public int someVariable;
public List<HasAClass> cList = new List<HasAClass>();
addHasAClass(HasAClass c){
cList.Add(c);
}
}
public class HasAClass{
public HasAClass(){
//Modify someVariable in some way????
}
}
public class HasASubClass : HasAClass{
public ComposedClass(){
//Modify someVariable in some way???
}
}
I having trouble finding the right words for this questions but here is what I am trying to do:
I am creating an aid for an RPG similar to dungeons and dragons. Each character can have a variety of special abilitys which can effect the characters in some way (both negative and positive). I am trying do this with a variety of subclasses which store the pertinent info and get added to the character at varying points in time. What I can't figure out is how to modify the properties of the Character(I called it Main Class in my example) when instances of the HasA class are added to it.
The HasAClass needs a reference to the owning instance, so that it can ask the parent for values and update them when required...
public class HasAClass
{
private MainClass _mainClass;
public HasAClass(MainClass mainClass)
{
_mainClass = mainClass;
_mainClass.someVaraible = 42;
}
}
You then need to pass the owner reference into the constructor of the HasAClass when they are created. If this is not possible at the time of creating the instance then you would instead need to assign it as a property after it has been created. Such as inside the addHasAClass method.

stackoverflowexception solution in C#

How can I prevent this exception to happen as I have to attain some values from one class and pass it to another class where as it's object is already in that class??
My first class is:
public partial class Rack : UserControl
{
ContainerAdmin a = new ContainerAdmin();
public Rack()
{
InitializeComponent();
}
public string getposition()
{
PositionLabel.Text = Regex.Replace(PositionLabel.Text, "[^0-9]+", string.Empty);
return PositionLabel.Text;
}
}
And my other class is :
public partial class ContainerAdmin : UserControl, IDataConsumer<ContainerAdminAssemblyAdapter>
{
public ContainerAdminAssemblyAdapter Adapter { get; set; }
Rack[] racking = new Rack[64];
}
A recursive loop will occur so I want to prevent this.
You have a situation where creating a ContainerAdmin creates an array of Racks which then creates a ContainerAdmin which then creates an array of Racks and so on. It's like a function calling itself without a stop condition and that's why you're getting the stack overflow.
To solve this problem, you have to restructure your program. In either the ContainerAdmin or Rack class, you shouldn't be creating new instances of the other. Using my psychic powers, I'd guess that the Rack objects should be provided with a preexisting ContainerAdmin object.
You are in a circular loop here. In other words you have created circular dependency here. That is why you are getting this exception.
Rack is creating instance of ContainerAdmin and ContainerAdmin is
creating instance of Rack.

Static / Shared variable across certain instances of a class but not others

This may just be me showing my lack of knowledge / bad programming practice, but i'm curious to know if:
a) This already exists
b) If it doesn't exist, if it's bad programming practice to do so
But here's my question:
Suppose I have a class, let's call it "Computer" and it holds data of all the computers in a company. Now, it just so happens that this company has thousands of Dell computers and thousands of HPs and nothing else. (Again please stick with me here, this is just an example to illustrate my point)
Now, I could define my class as follows:
Public Class Computer
Dim Type as string
Dim SerialNumber as string
Dim User as String
...
End Class
Now, in my code I create two lists:
Dim DellComps as new list(of computer)
Dim HPComps as new list(of computer)
Obviously, for the DellComps, all them will have .Type = "Dell" and for the HPComps, all will have .Type = "HP"
Now, I know I could set this variable in the constructor very easily, but I'm wondering if there is a smarter way to declare the variable inside the class - Similar to the VB Shared / C# Static statement where all the instances of the class share the same variable.
My thoughts are:
Inherit the class and create a shared variable in the child class
Just leave it as is and declare the Type var in the constructor
Maybe this is something that could be done via interfaces somehow
MOST PROBABLE - something i just don't know about
Thanks and I hope what I'm asking makes sense!!!
The closest thing you'd have is done with the abstract keyword. You would have an abstract class Computer, that would then be overridden by the concrete subclasses DellComputer and HpComputer. A crude (C#) example would be:
public abstract class Computer
{
public string Type { get; protected set; }
}
public class DellComputer : Computer
{
public DellComputer()
{
this.Type = "Dell"
}
}
You generally don't want to share a single variable among a ton of instances because that breaks encapsulation, and more realistically can become a big problem when attempting to unit test code. So the pure form of what you're talking about isn't a terribly good idea, but the realistic use case is pretty common, and definitely supported.
EDIT: As part of the comments below, here's a different approach that uses the very closely related virtual keyword!
public abstract class Computer
{
public virtual string Type { get; }
}
public class DellComputer : Computer
{
public override string Type
{
get {
return "Dell";
}
}
}
If you are always setting a flag in the constructor indicating the type of computer (which is NOT a typical business object scenario, where the type can be edited), chances are that you can really solve your problem using subclasses.
Subclass Computer to create DellComputer and HpComputer classes.
When creating lists of each type of computer, one approach is to have a master list of all computers and use Linq's Enumerable.OfType(TResult) to select instances that match the type you are interested in.
If indeed you want the type of class to be editable after the class is created, instead provide a property to modify the type of computer. You may for convenience provide a constructor overload that also sets the property (though I would shy away from that personally). If you do, have that constructor overload use the property to set the type.
UPDATE
Example of what the factory pattern might look like.
public abstract class Computer
{
public virtual string Type { get; }
}
public class DellComputer : Computer
{
public override string Type
{
get { return "Dell"; }
}
}
public class HpComputer : Computer
{
public override string Type
{
get { return "HP"; }
}
}
// Here I'm using an enum to indicate the type desired. You might use a string
// or anything else that makes sense in your problem domain.
public enum ComputerType
{
Dell = 1,
Hp = 2
}
public class ComputerFactory
{
public Computer Create(ComputerType type)
{
switch (type)
{
case ComputerType.Dell:
return new DellComputer();
case ComputerType.Hp:
return new HpComputer();
default:
throw new InvalidArgumentException();
}
}
}
// Usage would be something like:
List<Computer> computers = new List<Computer>();
computers.Add(ComputerFactory.Create(ComputerTypes.Dell);
computers.Add(ComputerFactory.Create(ComputerTypes.Dell);
computers.Add(ComputerFactory.Create(ComputerTypes.Hp);
You could create a class that has a collection and other data
In this case PC would not have a type.
public class Computers
{
private List<Computer> pcs= new List<computer>();
public List<Computer> PCs get { return { pcs; } };
public String Brand { get; private set; }
public Computers(string brand) {Brand = brand;}
}
Regarding a static variable. You don't want all members of the class share Brand.
With the said just repeat the data in the constructor.
If a Dell has the same Properties as an HP then I would use the same class.
If you stated buying a new brand do you really want to create a new class or subclass?
If you want a structured list of brands then I would use and Enum rather than a separate class for each brand.

Categories