Click here to Skip to main content
15,920,005 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
hi there,


is search for a possibility to access the same data in a base class form different instances of derived classes without a reference to the "right and only" data-storing-base class. how can i do something like that? *I hope my explanation is clear enough.


thanks for every meaningful answer.
delicious_cake
Posted

If I understood, simple make a static variable in the base class and you are done.
If it should not be seen by other classes, make it protected.
 
Share this answer
 
If you make the "right and only" data-storing base class a singleton, or static class, then yes. Unfortunately, then you can't usefully derive from it and have multiple instances of the derived classes.

To be honest, what you are trying to do sounds like bad design, and will probably give you more problems in the long run than you will solve in the short term.

What are you actually trying to do, that you think you need this?
 
Share this answer
 
If you have

public class BaseClass
{
   public string BaseClassProperty{get;set;}
}


then you have

public class FirstClass : BaseClass
{

}


and in some code you have

FirstClass instantiation = new FirstClass();


Then you can say

instantiation.BaseClassproperty = 42;


i.e. you access the data stored in the base class

If, however, you want to also do this

FirstClass instantiation = new FirstClass();
FirstClass otherinstantiation = new FirstClass();
instantiation.BaseClassProperty = 42;


and then want to do

int i = otherinstantiation.BaseClassproperty;


and want i to = 42, then you need to make the property Static

e.g.
public class BaseClass
{
   public static string BaseClassProperty{get;set;}
}


and then from anywhere in your code you can access the property..

int i = BaseClass.BaseClassProperty;




(this is pretty much what Paulo said above, but more verbose!)
 
Share this answer
 
Comments
delicious cake 21-Dec-11 8:05am    
excellent answer. thank you

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900