I need to determine if two classes have the same value.
Class A is the model of a record in a database.
The value of Class A is set as values of textboxes in a form.
If save is triggered,
I need to know if values on the textboxes are still the same as Class A.
I created Class B and equals it to class A.
Then replace Class B attribute values to what the textboxes has.
Then I compare if Class A == Class B.
My Problem is that after I update an attribute of Class B, the same attribute from Class A updates.
what can you suggest.
Consider turning your classes into structs so that they're copied by value, not by reference.
That way, if you do var b = a, the values inside a are literally copied over to b so that changing one will not affect the other. Then, you can just do a == b and it will automatically work by default. (Keep in mind -- if you have a huge amount of data inside your object instance, and you copy it many times, it could slow down your program/take up a lot of memory!)
Alternatively, implement the ICloneable interface, which requires you to implement a clone method.That way, you can do var b = a.clone(); rather then var b = a;. The clone method should instantiate a new version of your class and manually copy data over so that the two variables refer to different instances rather then the same one.
If you take this route, you probably need to implement custom equality comparators (see the IEquatable interface).
Create a new object for class B Which has a Copy of class A
Example:
classA objA= new classA();
classA objB= new classA();
objB=ObjA;
now Both Instances are different
Related
Hope I'm not asking something that has been already answered in here.
If my class B inherits from class A, does new B() create two instances in heap where B instance contains pointer to A instance, or there will be created only one instance of B including A members?
From Microsoft Inheritance article :
This is how an object is represented in memory, given the Class Publication directly inherits the class Object.
So a inherited class is an object that contains all information about itself but also about its base class.
It will create one instance of B, and that B is also an A.
it will create B instance that (because of inheritance) already include A members, if i understood your question well
It creates one instance and you can access all the members of both A and B on that instance. As stated A is of type B as well. I imagine that in the low level code there probably exists a pointer to A.
I have a three classes A, B, and C shown below
public class A
{
public void add(int i, int k)
{
}
}
public class B:A
{
public void AddInt()
{
add(1, 2);
}
}
public class C
{
public void AddInt()
{
A objA = new A();
objA.add(1, 2);
}
}
We want access the "A" class method Add, there are two ways
1) Initiate the "A" class, then access the Add method
2) Inherit the "A" class, then access the Add method
If both those ways provide the same functionality, then why does C# provide two ways to achieve the same functionality.
What is the difference between initiating a class and inheriting a class?
First off, the word you're looking for is instantiate, not initiate.
What is the difference between instantiating a class and inheriting a class?
Inheritance expresses the "is a kind of" relationship between two classes:
The New York Times is a kind of newspaper.
A giraffe is a kind of animal.
An apple is a kind of fruit.
In each of these cases the first kind of thing is the "more derived" type -- it is more specific -- and the second thing is the "less derived" type, or "base" type. It is more general. More things are fruits than are apples.
In C# when you establish an inheritance relationship between two classes, you get two things:
Assignment compatibility: you can use an expression of the more derived type where an expression of the base type is needed.
Member inheritance: all methods, events, indexers, operators, fields, properties and nested types of the base class are automatically members of the derived class. (Constructors and destructors are not inheritable).
Instantiation is the process of making a new instance of a type.
Here, let me give you a copy of today's New York Times.
Here, let me give you a giraffe.
Here, let me give you an apple.
So in C#:
class Fruit {}
class Apple : Fruit { } // Apple inherits from Fruit
class Program {
static void Main() {
Apple apple = new Apple(); // Instantiating a new Apple
}
}
Make sense?
It's not about C# at all, it's about basic OOP concepts, that C#, in this case, simply manifests, being object oriented and strong typed language.
"Initialization" is a creation of an instance of a given type: A in your case.
Second example is a Polymorphism , where you derive from a given type A, and creating derived type B, is able to access public/protected members of the A class.
The access behaviour is the same in this case, but origin of that is completely different.
you are comparing Humans with food ... right no comparison
Initiating cost you some RAM of your system.
Inheriting lets you enable reuseability of common code
These two ways are available because your add method is public in class A. Change it to protected if you want to use it only in inherited classes. Simply saying inheritance makes all properties and methods except of private ones available in inherited classes. In your case class B is inherited from class A and instance of class B itself would be your instance to call method add on. In class C you simply created an instance of class A and called method add on it. All of this concepts would be much cleaner to you if you'll read about Access Modifiers and Inheritance.
Think of a class as a template, or plan, for how to build something. When you then use the template or plan to build one (think of architect plans for a house, and one of the many houses built from those plans), the words we use to describe this process are "Instantiation" and "Initialization".
You instantiate an instance of the object (build the house) using the class template (architects plan), and then initialize it (paint and decorate the house).
Inheritance, on the other hand, refers to something completely unrelated, in how classes are defined, using another existing class as a foundation or *base*line from which to start the definition of a new class that will extend the foundation or base class. When one class inherits from another, it means that "instances" of the derived class automatically get all the stuff that was defined in the parent base class without having to redefine it in the child.
A class is a type and acts as a template that allows you to create objects of this type. The creation of such objects is also called instantiation. This instantiation process involves allocating memory for this object (allocation) and then initializing this object, i.e. give its fields initial values. The latter is called initialization.
Inheritance is something completely different. Inheritance is about creating a new class (template) by inheriting existing code from a base class (also called superclass, or parent class).
This new derived class (also called subclass or child class) serves as template for the creation of a new type of objects.
The derived class can modify the behavior inherited from its base class and extend its possibilities. Inheritance creates a relation between the classes. Subclasses are assignment compatible with the superclasses above them in the inheritance hierarchy.
I have two classes, one which inherits the other, for example:-
public class A
{
public string AA { get; set; }
public double AB { get; set; }
}
and
public class B : A
{
public double? BA { get; set; }
}
Now, I know that if I have an instance of object B, I can cast that as type A, but I have an instance of A that I want to instantiate as a type B object. I know I could put a constructor in B's class which copies all the property values over, but the base class, A, has quite a few properties and may well have more added, so I'm worried about missing one or forgetting to add it in to B's constructor when I add it to A. Is there an easy way of doing this, please?
-------Edit------
Thanks folks, not my use-case unfortunately, it's a question a mate's fired at me. As far as I'm aware there are issues and he can't change the base class. As I understand it, the base class is one that hooks into a database call, he then wants to grab that data and add some extra properties for an admin editing screen which his code will then use to update the base data object's properties. My first reaction was to have the base object as a property of his object, but there's a reason it's significantly easier for him to have it "flattened" with the tools he's using. I didn't think there was a way of doing this, but I thought I'd check in case I was missing something - I thought it would be easier to just ask the basic question, rather than include the background, which would probably just raise more questions and muddy the water (AFAIK he's suffering from "circumstances beyond his control", with this).
I know I could put a constructor in B's class which copies all the property values over, but the base class, A, has quite a few properties and may well have more added, so I'm worried about missing one or forgetting to add it in to B's constructor when I add it to A. Is there an easy way of doing this, please?
Typically, this is a sign of a design flaw. I would rethink your design first, and determine whether this is truly necessary, or if there is another approach you can use here. That being said...
There is no easy way to do this. If you need a B instance to be created from your A instance, you'll really need to copy the values over to the new instance.
A better option, however, would potentially be to add a (potentially protected) constructor to A that sets all of these properties, given another A instance. B could then use this to create itself, which at least keeps the requirements for matching all of the properties within the class that defines them. This should make it easier to maintain this over time.
I agree with the other remarks, you're better off using a different design, such as composition instead of inheritance.
Composition, shown below, allows you to modify class A without requiring any changes to class B.
public class B
{
// Constructor
public B(A A) { this.A = A; }
// Class A as a read-only property
public A A { get; private set; }
// Other properties of class B
public double? BA { get; set; }
}
Reverse Polymorphism is not supported in c#.
As Reed Copsey said, this is typically a sign of a design flaw. I would re-work the class diagram if you need something like this to work. It sounds like some sort of mistake was made in the inheritance architecture somewhere.
If all you need is for both child and parent to implement common methods so that when either of the objects is passed to some function it can operate on some common methods on the passed-in object, then just have the two of them implement the same interface (polymorphism), or type the function parameter as the base class and make sure the methods exist on the base class.
I'm trying to make a small application that can edit the data files from an earlier project. I have access to that projects "data classes" (pretty dumb classes whose main purpose is to expose it's (public) member variables) that can read/write to the files. All I have to do is make a GUI that can edit the different member variables that each data class have (preferably without modifying the data class) and I'm trying to figure out how to do this so that it will be easy to adapt for future changes/additions.
(I don't feel like I can assume that all member variables should be editable, might only be a selection of them).
All the data can be converted to/from strings (numbers and text) and I don't see much problem in generating textboxes and/or something like a DataGridView in the GUI, but I'm not sure as to how I would like to represent the data needed to generate those.
My first thought was to use a list with all variables for each data class. With each row in the list containing the name+description of the variable (for the GUI), a pointer to the variable in the data-class and perhaps some form of validation-function for different variables.
Store that list in a class that inherits the original data-class (and that implements an interface/abstract-class for any specific GUI-related functions (load/save etc.)).
The thing that makes me worry about this solution is just that I feel like this should be a somewhat common problem and I'm a bit rusty when it comes to OO and this solution smells like something I'd write if I had to do it in C.
There might even be a handy language construct, design pattern or something that is suitable but I don't know what to search for.
Does this approach even seem sensible?
Reflection is your friend in this case. Your data classes have a structure which can be explored using that class's Type. A Type is the base class for metadata concerning a class or structure, and includes methods to, for instance, get a list of all fields, properties and/or methods belonging to that class. The objects representing these class "members" can then be used to set or get field or property values, or invoke methods, given an instance of an object of that type.
A reflective algorithm can be designed to handle any object structure it is given, and it doesn't have to know those structures at compile-time unlike an algorithm based on static types. The downside? It's slow, and you get very little compile-time checking of your algorithm so it can fail at run-time in unexpected ways.
Here's something to get you started:
//statically set up an instance of some arbitrary object
MyClass myObject = new MyClass();
myObject.Field1 = "Hello";
myObject.Field2 = "World";
//This method is available on any object, and produces a Type representing the class definition
Type myType = myObject.GetType();
//C# also has a typeof() keyword that works when you have a static type and not an instance
myType = typeof(MyObject);
//Interrogate the Type instance to get its fields
FieldInfo[] fields = myType.GetFields();
//then, iterate through the fields to perform some (useful?) work.
//Here, we are outputting a list of paired field names and their current values.
//You will probably want to instantiate a Label and Textbox representing this value
//and show them on a Form.
foreach(FieldInfo field in fields)
Console.WriteLine(String.Format("{0}: {1}", field.Name, field.GetValue(myObject));
To handle editability, you will need some sort of record of what the user has permission to change and what they don't. If that information will never change from user to user, you can incorporate that information into the data class itself using attributes (which won't change the "interface" of the object; it'll still have all the same members, but those members will have additional metadata). You could also create another set of classes that implement an interface defining each one as a set of "field permissions" for its parent class, and then you can dynamically construct an instance of the "field permission" class with a Type instance representing your object definition, and knowledge of the name of the interface that field permission objects implement.
I have an class named Foo. This class contains a collection of child objects of type FooChildBase, but I also have a further class of type FooChildTwo which inherits from FooChildBase.
Class Foo
Public Children As IList(Of FooChildBase)
End Class
Class FooChildBase
Public Info As String
End Class
Class FooChildTwo
Inherits FooChildBase
Public ExtraInfo As String
End Class
This all works fine. Now I need to use a specialisation of my Foo object with extra information.
Class FooSpecial
Inherits Foo
Public SpecialInfo As String
End Class
Class FooChildSpecial
Inherits FooChildBase
Public SpecialChildInfo As String
End Class
What I would like to do is have my FooSpecial Class treat it's Children collection as if they were FooChildSpecial objects, but still be able to add FooChildTwo objects to it. Is this possible and if so how can it be done?
EDIT
I think my original question was incorrect. I need to FooChildSpecial class to wrap any of the objects in the Children collection with the extra values, whether they are FooChildBase or FooChildTwo or XXX.
Hope this makes sense! Please let me know if more clarification is needed.
James
In order for FooSpecialChild to "Wrap" FooChildTwo, it either has to inherit from it or implement the same interface (IFooChildTwo). Unfortunately, you cannot conditionally inherit or implement ... it is either always or never. As such, your FooSpecialChild class can inherit from FooChildTwo, but then it will always be a FooChildTwo. Same if it implements the same interface as FooChildTwo.
The design pattern you laid out will work correctly. Since both FooChildSpecial and FooChildTwo inherit from the same base class, and the list is of that base class type, it will work out. You'll just have to check the type of the object when you're pulling from the .Children property.
After copy+pasting your code into a sample project, I could successfully do:
var foo = new Foo();
foo.Children = new List<FooChildBase>();
var special = new FooChildSpecial();
special.SpecialChildInfo = "special";
foo.Children.Add(special);
var two = new FooChildTwo();
two.ExtraInfo = "two";
foo.Children.Add(two);
Which shows that you can add both FooChildSpecial and FooChildTwo to your original list.
What do you mean by "treat as if they were FooChildSpecial" objects? Do you mean access methods that exist only in FooChildSpecial objects?
In this case you will need to cast them to FooChildSpecial.
However, it is better to just let FooSpecial treat them as FooChildBase objects, but have in FooChildSpecial and FooChildTwo that override the base methods to get different behaviors for the two subclasses.
I also have a feeling that you really don't need the FooSpecial class at all, but I could be wrong. I suspect that the extra information and special information could just be combined into "information" and if they need different types of information to initialize the class wtih the different types.
You could purhaps do it with generics that you have a base class which contains a list of Type T. When you define Foo and FooSpecial you spesify what T is.