Apologies for the vague title, but I am not really sure how else to explain it.
Given Class A, B and C.
If Class A contains a List, how can I preserve the data in that list so that Class B and C can access the data in the list (even if B and C both new up their own instance of Class A)?
Classes B and C must create their own instances (this is out of my control).
I am using this class as my object data source, and let's say I cannot modify the contents of Class C.
Following is an example class:
[DataObject]
public class Product
{
public string Name {get; set;}
public string Category {get; set;}
public int ID {get; set;}
public List<Product> ProductList =
new List<Product>();
[DataObjectMethod(DataObjectMethodType.Select)]
public IEnumerable<Product> GenerateReport()
{
return ProductList;
}
}
Use static as defined here: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/static
Then you will be able to access the class properties instead of instance properties.
You have multiple options to implement this. As said in other answer you can use Static property/field in Class A for accessing list.
Second option is to use Dependency injection. Create constructors of class B and class C so that they must be initialized by passing in instance of A.
e.g.
class A
{
public List<object> AList {get;set;}
}
class B
{
private A localInstance;
public B(A instance)
{
localInstance = instance;
}
public void SomeMethod()
{
// access to list from instance of A
var a = localInstance.AList
}
}
// Similar implementation for class c
Related
Is there a way, and not using reflection, of elegant get only child propeties of an object?
For example:
class A
{
public string PropA;
}
class B : A
{
public string PropB;
}
class C
{
var classB_instance = new B();
/* Only class B properties without parent so B.PropB; but no B.PropA;
}
I know it would be possible with reflection, but if this can be avoided?
You could create a specific interface for your inherited class like say
interface ISpecificB {
string PropB;
}
and then Create your class like
public class A {
public string PropA;
}
public class B: A, ISpecificB {
public string PropB;
}
and only make the variable as specific as ISpecificB when creating it or returning it from a function
ISpecificB classB = new B();
classB.PropA // shouldn't be available
However, classB could still be casted as B or A which would give access to the propA and it might increase complexity in your solution
Whether you can do this way ?
class A
{
private string PropA;
}
class B : A
{
public string PropB;
}
class C
{
var classB_instance = new B();
}
You could mark PropA as private, look at https://msdn.microsoft.com/en-us/library/ms173121.aspx:
private
The type or member can be accessed only by code in the same class or struct.
just a short note: most of the time, I use reflection to do exactly the opposite: access things I am not allowed, for example, because they are private... ;-) reflection is not a "tool" to hide something, AFAIK. it opens every door which is usually locked ;-)
You can use the protected accessibility modifier:
The type or member can be accessed only by code in the same class or struct, or in a class that is derived from that class.
public class A
{
protected string PropA { get; set; }
}
public class B : A
{
public string PropB { get; set; }
}
public class C
{
var classB_instance = new B();
//You can't access classB_instance.PropA
}
Declare variable PropA of Class A as private variable(as show in below code):
class A
{
private string PropA;
}
Is it possible to write a class that acts like the super class of two other classes.
For example I have class A and class B. A and B share similar properties, but since I did not code A or B they do not extend an interface or class. Is it possible for me to create this super class so that when I generalize my code it can handle class A or B.
If this super class could be created this is some of what I would like to do in my class
class A
{
string Name { get; set;}
//does stuff
//I can't change this class
}
class B
{
string Name { get; set;}
//does similar stuff
//I can't change this class either
}
class MyClass
{
//I would like to create a list that can include both class B and class A
List<(pseudo superclass of A and B)> list;
//Both class A and class B have a name, I would like to get the name given a type of A or B
public (pseudo superclass of A and B) GetName((pseudo superclass of A and B) AorB)
{
//Write that name to the console
Console.WriteLine(AorB.Name);
}
}
Is this kind of wrapping possible, or will I need to do more work inside of MyClass (such as overloading methods) in order to accomplish what I need.
I'd suggest,
1 Create an interface:
interface IWrapper
{
string Name { get; set; }
...
}
2 Create wrapper classes:
class WrapperA : IWrapper
{
private A _a;
public WrapperA(A a) { _a = a; }
public Name
{
get { return _a.Name; }
set { _a.Name = value; }
}
// other properties here
}
and likewise for a BWrapper around B.
Then you can create your class as:
class MyClass
{
List<IWrapper> list;
public string GetName(IWrapper aOrB)
{
Console.WriteLine(aOrB.Name);
}
}
for e.g I have a class student and in same class the object is created itself.
class student
{
public static void Main ()
{
//......
//......
}
student s= new student();
}
If you declare the class as your sample code shows it will not work.
You use an initializer that creates an instance (of the same type) that will call the initializer that creates an instance that will call the initializer...
You'll end up in an StackOverflowException.
If you need a nested structure of the same kind you should think of creating it lazy on first access.
Maybe the code could look like this:
class student
{
Lazy<student> s = new Lazy<student>(() => new student());
}
This will give you the possibility to create an instance. At the first access of s.Value a new instance of student will be created. The logik of iterating over all instances will create an StackOverflowException or not.
A singleton is created as a static variable.
class StudentSingleton
{
public static readonly StudentSingleton Instance = new StudentSingleton();
private StudentSingleton() { }
}
The difference is that there is no instance variable created of the same kind.
class A
{
public A InstanceA{get; set;}
}
It's called self-association and though it is a common practice in some cases but you'd better avoid using it without a good cause.
Check this for example:
http://sce.uhcl.edu/helm/rationalunifiedprocess/process/modguide/md_assoc.htm#Self-Associations
Some example:
public class Person
{
public string Id {get; set;}
public string Name {get; set;}
public DateTime BirthDay {get; set;}
// ... some other properties
public Person Father {get; set;}
public Person Mother {get; set;}
}
Here we use self-association in class because instance of Person in analogy to real life certainly knows who his parents are and they are Persons too.
As to your case just change code to:
class Student
{
}
class Program
{
public static void Main ()
{
//......
//......
Student s = new Student();
}
}
Hi My code is as follows
public partial class Class1:InheritBase1
{
public Class1()
{
//Access table1 here
}
}
public class InheritBase2
{
protected DataTable table1{get;set;}
}
I need to access table1 from InheritBase2 class to my class.
As C# doesn't allow multiple inheritance what are the possible ways to achieve this ?
Thank's all.
You could easily solve this using composition instead of inheritance.
Say there's a class A and a class B. A has a B.
public class A
{
public B AssociatedB { get; set; }
}
Why...?
could you please elaborate – kyle
In object-oriented programming there're two approaches to create relationships between objects. Either of them are necessarily hierarchical.
If you end up thinking some object is something, we'll be talking about inheritance. For example, a cat is an animal. That is, a class cat derives from animal.
In the other hand, if you end up thinking some object has a X thing, we'll be talking about composition. For example, a car has an engine.
At the end of the day, if you are using inheritance in order to share a reference to a DataTable, I really encourage you to use composition instead, because your class has a DataTable:
public class A
{
public DataTable Table { get; set; }
}
public class B
{
public DataTable Table { get; set; }
}
DataTable someTable = new DataTable();
// Both class instances share the same DataTable
// because you set the same object to both
// class properties
A someA = new A();
someA.Table = someTable;
B someB = new B();
someB.Table = someTable;
You can benefit form the composition.
class A : B {
}
can be replaced as
class A {
B b
}
If you want that A and B can be used in the same contenxt you need to intruduce a interface.
The interface allow you to define abstract functionality and have various implementations for it.
interface ISampleInterface
{
void SampleMethod();
}
In case when we have
class B : ISampleInterface
{
void SampleMethod() {
//Do some action
}
}
Now your class A can or inherit form B in odrder to access to sample method or use composition.
class A : ISampleInterface {
B b;
void SampleMethod() {
b.SampleMethod();
}
}
Then i code you can use this like
ISampleInterface sa = new A();
ISampleInterface sb = new B();
sa.SampleMethod(); //Call B through A
sb.SampleMethod(); //Call B
This is only bired description for more you should follow a tutorial about Object Oriented Programming.
I'm looking for a way to assign to the base part of a derived class from a variable of the base class, without having to explicitly assign each assignable property one by one. Put another way: starting from a variable of the base class, I'd like to end up with a variable of the derived class that has all of the assignable base properties set, without having to remember what they are, or edit code if they change.
I create view models as derived classes from the base class of an Entity that's about to be edited. Usually this is just to add the IDs for navigation properties so they can be returned by the POST. For example:
public class ThingEditView : Thing
{
public int UsefulID { get; set; }
}
It gets used like this:
var foo = new ThingEditView
{
UsefulID = thisThing.Useful.ID,
A = thisThing.A,
B = thisThing.B,
/* and potentially many more properties from the base class Thing */
};
return View(foo);
But, I run into trouble when I add properties to the base class Thing and forget to edit all the places where I initialize a ThingEditView or a ThingDetailView, etc. I would love to be able to say
var foo = new ThingEditView
{
base = thisThing,
UsefulID = thisThing.Useful.ID
};
and let the compiler figure out which fields to assign. Is there a way to do this?
Thanks for insight!
void Main()
{
var thisThing= new ThingEditView {UsefulID = 1, A = 2, B = 3};
var foo = new ThingEditView(thisThing);
//foo.Dump();
}
// Define other methods and classes here
public class Thing
{
public int A {get; set;}
public int B {get; set;}
public Thing() {}
public Thing(Thing thing)
{
this.A = thing.A;
this.B = thing.B;
}
}
public class ThingEditView : Thing
{
public int UsefulID {get; set;}
public ThingEditView() {}
public ThingEditView(Thing thing) : base(thing) {
}
public ThingEditView(ThingEditView view) : base(view) {
this.UsefulID = view.UsefulID;
}
}
I would choose for an automapper.