I have a class called Star, and it has a
public List<Planet> Planets = new List<Planet>();
There is a method that creates the Planets with the variables needed, though I want some of the information about the star accessible in the planet class.
right now there are 4 variables I construct the 'Planet Class' with but I need about 6 of the variables from the 'Star Class' available in the 'Planet Class'.
Is there a way to have a reference to the parent star in the planet class? and how would I pass the reference to the Planet?
Thanks!
You can include a reference in the Planet class to the Star. You can then create a constructor that takes that reference, like so:
public class Planet
{
private Star orbits;
...
public Planet(Star orbits)
{
this.orbits = orbits;
...
}
...
}
You can then instantiate it from in Star like this:
public List<Planet> Planets = new List<Planet>(this);
There are plenty of ways to accomplish this, just one idea:
What about making a parameter for your contstructor like:
private List<Star> _solarSystem;
Planet(List<Star> solarSystem)
{
this._solarSystem = solarSystem;
}
From OO point of view it would be better to have instead of the list a class. I assume the code you have posted is also in some class, so how is your class called ?
private SolarSystem _solarSystem;
Planet(SolarSystem solarSystem)
{
this._solarSystem = solarSystem;
}
A typical solution is to inject an interface that the class implements into the dependent class (dependency injection). Something like this for your case:
internal interface IStar
{
void Method1();
string Property1 { get; }
...
}
internal abstract class Star : IStar
{
protected Star()
{
foreach(string planetName in planetNames)
{
Planet p = new Planet(planetName, this);
Planets.Add(p);
}
}
public void Method1()
{
...
}
public string Property1
{
get { return string.Empty; }
}
}
internal class Planet
{
string name;
IStar parentStar;
internal Planet(string name, IStar parentStar)
{
this.name = name;
this.parentStar = parentStar;
}
}
Doing it in this fashion allows you to pass in different classes that implement IStar if needed. Maybe you have the base abstract class Star, which is inherited by ClassAStar, DwarfStar, etc. The Planet doesn't care what kind of star you pass in, as long as it implements the IStar interface. This promotes loose coupling, making your code easier to maintain.
Use dictionary like this:
IDictionary<Star, IList<Planet>> planetSystems = new Dictionary<Star, IList<Planet>>();
Related
This question sounds very common, but I have no idea how i should implement it.
My scenario:
Question: How to implement DirectionTile?
Behavior implementation of DirectionTile:
abstract class DirectionTile
{
public Point Direction;
public Tile Next => Board.GetTile(Coords + Direction);
}
As you can see property Coords will be from the base class (?), which is Tile.
Both RailTile and SailTile are DirectionTiles. However, I can not just inherit from DirectionTile, as SailTile needs to inherit from WaterTile and this would case 2 relations with Tile (really want to use polymorphism like this).
I hope somebody can help me with this problem, that I can not solve. Let me know if my explanation is clear enough.
If i understand correctly, DirectionTile is a behaviour implemented by entity.
Use simply an Interface IDirectionTile, and to prevent multiple implementation you could provide an extension Methods :
public interface IDirectionTile
{
}
public static class TileExtensions
{
public static void GetDirection(this IDirectionTile th)
{
}
public static void Next(this IDirectionTile th)
{
}
}
Do it like this: Base from your diagram Tile will be your base/parent class and all other classes will be its child class. which then will inherit the property and function(s) that the Tile has. For DirectionTile i think it's a separate entity/class where you will just instantiate WaterTile and RailTile
public abstract class Tile
{
private Point direction;
public Point Direction
{
get { return direction; }
set { direction = value; }
}
public abstract string someFunction();
}
Now to inherit the property and the function:
public class WaterTile : Tile
{
//all property and functions now are accessible from the Tile base class
private string somevariable;
public string Somevariable
{
get{return somevariable;}
set{somevariable=value;}
}
public override string someFunction()
{
//return "something";
}
}
public class SailTile : WaterTile
{ //if there are additional properties/functions in your WaterTile it will be accessible by this class (SailTile) but not to other class
//in this case Somevariable is accessible in this class
}
I have a base and derived class like so:
public abstract class MyBase
{
protected string _data;
protected string GetData_Internal() {return _data;}
protected abstract void SetData(string data);
}
public class MyDerived : MyBase
{
protected override void SetData(string data) {_data = "my data";}
public static string GetData()
{
var instance = new MyDerived();
return instance.GetData_Internal();
}
}
The desired usage of this class is like this:
string data1 = MyDerived.GetData();
string data2 = MyDerived2.GetData(); // another class dervied from MyBase
I can't make the classes static, because static classes and derived classes don't play well together. So I made the function GetData() static, and this allows me to use the class like I want to.
I am going to have multiple classes that all identical to MyDerived, except for the data values set in SetData().
I would like to move GetData() out of the derived class and into the base class so that I'm not duplicating that code in every single derived class.
I can't figure out how to do that, because a static method in the base class has no idea what type of object to new up.
So, is there any way to do what I'm trying to do, keeping a static interaction with the class, while avoiding code duplication to make it happen?
If you are working with static data, maybe what you need are singleton objects that can be instantiated only once. They have the advantage of supporting inheritance and interface implementation, as well as being accessible statically. Also, unlike static classes, they can be passed as arguments to methods and stored in fields, properties and variables.
You can use properties instead of getter and setter methods. This simplifies your base class:
public abstract class MyBase
{
public string Data { get; set; }
}
You can implement the singleton pattern like this:
public class MyDerived : MyBase
{
#region Singleton Pattern
public static readonly MyDerived Instance = new MyDerived();
private MyDerived()
{
}
#endregion
}
Create a public static readonly field that returns the only instance of the class and make the constructor private in order to forbid creating instances outside of the class itself. The constructor can also initialize the value of Data if required.
You can use the singletons like this:
MyDerived.Instance.Data = "my data";
string data = MyDerived.Instance.Data;
MyDerived2.Instance.Data = "my data 2";
...
See also: Implementing Singleton in C# for various ways of implementing the singleton pattern.
First, I am not completely sure what it is you are trying to accomplish. So, I am making no comment on if any of this is a good idea. You can get behavior that acts somewhat like overridden methods on base classes with statics. Instead, you overwrite the base then call into it. I do something similar to this for fetching instances or collections of instances from the class:
public class Dog
{
public static Dog GetById(int dogId)
{
//Return dog
}
}
public class Lab : Dog
{
public new static Lab GetById(int dogId)
{
//Return same dog, as a lab
}
}
A quick and terrible, but hopefully useful, version might start like the following. I might be able to make it into something practical if I understand your intentions a bit better.
public abstract class MyBase
{
public static string GetData()
{
return "BASE STUFF";
}
}
public class MyDerivedA : MyBase
{
protected const string MySpecialData = "AAAAAA";
public new static string GetData()
{
return MyBase.GetData() + MySpecialData;
}
}
public class MyDerivedB : MyBase
{
protected const string MySpecialData = "BBBBBBB";
public new static string GetData()
{
return MyBase.GetData() + MySpecialData;
}
}
How can i check/evaluate the exact type of T without an object for T. I know my question maybe confusing but consider this...
public abstract class Business
{
public abstract string GetBusinessName();
}
public class Casino : Business
{
public override string GetBusinessName()
{
return "Casino Corp";
}
}
public class DrugStore : Business
{
public override string GetBusinessName()
{
return "DrugStore business";
}
}
public class BusinessManager<T> where T : Business
{
private Casino _casino;
private DrugStore _drugStore;
public string ShowBusinessName()
{
string businessName;
if (T == Casino) // Error: How can I check the type?
{
_casino = new Casino();
businessName = _casino.GetBusinessName();
}
else if (T == DrugStore) // Error: How can I check the type?
{
_drugStore = new DrugStore();
businessName = _drugStore.GetBusinessName();
}
return businessName;
}
}
I just want to have something like this on the client.
protected void Page_Load(object sender, EventArgs e)
{
var businessManager = new BusinessManager<Casino>();
Response.Write(businessManager.ShowBusinessName());
businessManager = new BusinessManager<DrugStore>();
Response.Write(businessManager.ShowBusinessName());
}
Notice that I actually didnt create the actual object for Casino and Drugstore when I call the BusinessManager, I just pass it as generic type constraint of the class. I just need to know exactly what Type i am passing BusinessManager to know what exactly the Type to instantiate. Thanks...
PS: I don't want to create separate specific BusinessManager for Casino and Drugstore..
You can also comment about the design.. thanks..
ADDITIONAL: and what if class Casino and DrugStore is an ABSTRACT CLASS =)
You can write
if(typeof(T) == typeof(Casino))
but really this type of logic is a code smell.
Here's one way around this:
public class BusinessManager<T> where T : Business, new() {
private readonly T business;
public BusinessManager() {
business = new T();
}
}
but personally I'd prefer
public class BusinessManager<T> where T : Business {
private readonly T business;
public BusinessManager(T business) {
this.business = business;
}
public string GetBusinessName() {
return this.business.GetBusinessName();
}
}
You should do
public class BusinessManager<T> where T : Business, new()
...
T _business = new T();
string businessName = _business.GetBusinessName();
return businessName;
I don't know about C# syntax, but is it not possible to do:
public class BusinessManager<T> where T : Business, new()
{
private T _business;
public string ShowBusinessName()
{
string businessName;
_business = new T();
return _business.GetBusinessName();
}
}
Since other guys have already shown various answers to your first question, I would like to address the second one: design.
1. Role of BusinessManager
Actual role of the BusinessManager class in your example is not too clear. Since this class is generic, and it shouldn't be concerned with the actual type of T, then it does nothing more than add another unnecessary layer between the Business class and the rest of the program.
In other words, you can simply use:
Business casino = new Casino();
Response.Write(casino.GetBusinessName());
Business drugStore = new DrugStore();
Response.Write(drugStore.GetBusinessName());
Wrapping this in another generic class doesn't help you a lot. On the other hand, if you want to have some common functionality for all these classes, you can either add it directly to your abstract class, or extract an interface and create extension methods for that interface.
2. Using properties for getters
Second thing, using a property is more appropriate when you have a simple getter method. In other words, you should replace GetBusinessName() method with a Name property (I also omitted the "Business" from the name because it is not necessary:
public interface IBusiness
{
string Name { get; }
}
public abstract class Business : IBusiness
{
public abstract string Name { get; }
}
public class Casino : Business
{
public override string Name
{
get { return "Casino Corp"; }
}
}
public class DrugStore : Business
{
public override string Name
{
get { return "DrugStore business"; }
}
}
And then you can use it like this:
IBusiness casino = new Casino();
Response.Write(casino.Name);
IBusiness drugStore = new DrugStore();
Response.Write(drugStore.Name);
Also, you can see that I have introduced a IBusiness interface. The reason for doing so is to allow you to implement this interface in more diverse ways. Right now, you will try to derive all your classes from the abstract Business class, and try to extract as much of the common functionality in the abstract class (that's the purpose of the class).
But extracting lots of common functionality comes with a cost: there is always a possibility that you will come up with a need to create a class which isn't derived from Business. If you are accessing all these methods through the IBusiness interface, then other parts of your program won't care if that implementation is derived from Business or not.
Since GetBusinessName really applies to the type and not instances of the type, you might consider using DescriptionAttribute (or your own BusinessNameAttribute) instead of an overridden property and have your BusinessManager get the business name from the attribute.
[Description("Casino Corp")]
public class Casino : Business
{
}
Now you no longer need to instantiate the business just to gets its name. To get the description, you use:
public string ShowBusinessName()
{
var attribute = Attribute.GetCustomAttribute(typeof(T), typeof(DescriptionAttribute)) as DescriptionAttribute;
if (attribute == null)
return "Unknown business";
return attribute.Description;
}
You can do something like this:
if (typeof(T) == typeof(SomeType))
{
// Same
}
define a BusinessManager class as bellow:
public class BusinessManager<T> where T : Business
{
Business biz;
public BusinessManager()
{
biz = new T();
}
public string ShowBusinessName()
{
return biz.GetBusinessName();
}
}
and use it as bellow:
var businessManager = new BusinessManager<Casino>();
Response.Write(businessManager.ShowBusinessName());
var anotherBusinessManager = new BusinessManager<DrugStore>();
Response.Write(businessManager.ShowBusinessName());
The way you using you will lost encapsulation
In VB.net you can use the GetType pseudo-function on a generic type parameter to get a reflection Type object. I would guess C# should have an equivalent. If for whatever reason you can't use something like that, you could create an array of 0 elements of the desired type, and then check the type of that array. That would probably be cheaper than instantiating an element of the unknown type.
So, I'd like to hear what you all think about this.
I have a project where three different inheritance paths need to all implement another base class. This would be multiple inheritance and isn't allowed in C#. I am curious how I can implement this without code duplication.
EDIT: I don't own the three classes. The three classes are from 3rd party code. So I cannot make them all extend my base class.
Right now I am using three different classes, each one extending a different base class. Then I have the same code in each of the three abstract classes.
I could use a single interface, but I would still need to duplicate the code.
I could make some kind of static class that implements the code and then reference that in each of the 3 abstract classes. It would eliminate the duplication, but, I am not sure how I feel about this. I could implement Extensions methods on the interface, but then the interface itself would be empty and the extension methods (containing the duplicate code) would be in a totally different file, which seems not quite right. Plus I can't implement properties in extension methods...
How can I factor out the code duplication here?
EDIT, inheritance tree:
class Class1 : 3rdPartyBaseClass1 { }
class Class2 : 3rdPartyBaseClass2 { }
class Class3 : 3rdPartyBaseClass3 { }
I have code I want to be in each of the above Classes, but I cannot add it to the 3rdPartyClasses.
Create an interface that Class1, Class2, and Class3 can implement. Then put your code in extension methods so it will apply to all.
interface IMyInterface {
void Foo(); //these are the methods that these
//classes actually have in common
void Bar();
}
public class Class1 : 3rdPartyBaseClass1, IMyInterface {
// whatever
}
public static class IMyInterfaceExtensions {
public static void CommonMethod(this IMyInterface obj) {
obj.Foo();
obj.Bar();
}
}
public static class Program {
public static void Main() {
var instance = new Class1();
instance.CommonMethod();
}
}
OK, you can do something similar to my previous suggestion, and also similar to recursive's suggestion. For the functionality you require in all three of your derived classes, you can create a single Interface along with a single class (call it "Implementer" for kicks) that implements that Interface (and that has the actual code you want executed with each call).
In each of your derived classes, then, you implement the Interface and create a private instance of Implementer. In each of the interface methods, you just pass the call along to the private instance of Implementer. Because Implementer and your derived classes all implement your Interface, any changes you make to the Interface will require you to modify Implementer and the derived classes accordingly.
And all your code is in one place, except for all the lines passings the calls on to the private instance of Implementer (obviously multiple inheritance would be better than this, but you go to war with the army you have, not the army you wish you had).
Update: what about just adding a public instance of your class to each of the derived classes?
public class DerivedClass1 : ThirdPartyClass1
{
public MyClass myClass = new MyClass();
}
Or if you care who Demeter is and you get paid by LOC:
public class DerivedClass1 : ThirdPartyClass1
{
private MyClass _myClass = new MyClass();
public MyClass myClass
{
get
{
return _myClass;
}
}
}
Then you'd just call the MyClass methods like this:
DerivedClass1 dc1 = new DerivedClass1();
dc1.myClass.DoSomething();
This way, we could all go to sleep.
Similar to MusiGenesis's suggestion, if you need the functionality of the 3rd party classes but do not have to descend from them, you could use composition as follows:
class ThirdPartyBaseClass1
{
public void DoOne() {}
}
class ThirdPartyBaseClass2
{
public void DoTwo() { }
}
class ThirdPartyBaseClass3
{
public void DoThree() { }
}
abstract class Base
{
public void DoAll() { }
}
class Class1 : Base
{
public void DoOne() { _doer.DoOne(); }
private readonly ThirdPartyBaseClass1 _doer = new ThirdPartyBaseClass1();
}
class Class2 : Base
{
public void DoTwo() { _doer.DoTwo(); }
private readonly ThirdPartyBaseClass2 _doer = new ThirdPartyBaseClass2();
}
class Class3 : Base
{
public void DoThree() { _doer.DoThree(); }
private readonly ThirdPartyBaseClass3 _doer = new ThirdPartyBaseClass3();
}
This also gives you the freedom to define whatever interfaces you want and implement them on your classes.
Sounds like you need to insert the new abstract class into the inheritance tree at whatever point those three paths come together, but there really isn't enough information to tell. If you could post some of your inheritance tree, that would help a lot.
I think you may want to use composition instead of inheritance. Exactly how to do this depends on what the third party classes look like, and what your own code looks like. Some more specific code relating to your problem would be helpful, but for example, suppose you want to have three different third party GUI widgets that all need to be customized with your own initializer code.
Case 1: Suppose your third party widgets look like:
public interface IThirdPartyWidget {
public void doWidgetStuff();
}
public class ThirdPartyWidget1: ThirdyPartyWidget implements IThirdPartyWidget {
...
}
public class ThirdPartyWidget2: ThirdPartyWidget implements IThirdPartyWidget {
...
}
You can do:
public class MyWidget implements IThirdPartyWidget {
private IThirdPartyWidget delegateWidget;
public MyWidget(IThirdPartyWidget delegateWidget) {
this.delegateWidget = delegateWidget;
}
public void doWidgetStuff() {
delegateWidget.doWidgetStuff();
}
}
Case 2: Suppose you absolutely need to extend those widgets, and you have to refactor your own code:
public class MyWidget1: ThirdPartyWidget1 {
public void myMethod() {
runMyCode();
}
private void runMyCode() {
//something complicated happens
}
}
public class MyWidget2: ThirdPartyWidget2 {
public void myMethod() {
runMyCode();
}
private void runMyCode() {
//something complicated happens
}
}
This can become:
public class MyCodeRunner {
public void runMyCode() {
//...
}
}
public class MyWidget1: ThirdPartyWidget1 {
private MyCodeRunner myCode = new MyCodeRunner();
public void myMethod() {
myCode .runMyCode();
}
}
public class MyWidget2: ThirdPartyWidget2 {
private MyCodeRunner myCode = new MyCodeRunner();
public void myMethod() {
myCode .runMyCode();
}
}
Hope this makes sense!
I have a class that has private fields... (cars)
I then inherit from this class... (Audi)
In the (Audi) class, when I type this. in the constructor...
the private fields are not available...
Do I need to do anything special to expose this private fields in (cars) class so that they are accessible via this. in (Audi class)?
One (bad) option is to make the fields protected - but don't do this; it still breaks proper encapsulation. Two good options:
make the setter protected
provide a constructor that accepts the values
examples:
public string Name { get; protected set; }
(C# 2.0)
private string name;
public string Name {
get { return name; }
protected set { name = value; }
}
or:
class BaseType {
private string name;
public BaseType(string name) {
this.name = name;
}
}
class DerivedType : BaseType {
public DerivedType() : base("Foo") {}
}
Philippe's suggestion to declare the fields as protected instead of private will indeed work - but I suggest you don't do it anyway.
Why should a derived class care about an implementation detail of how the data is stored? I suggest you expose protected properties which are (currently) backed by those fields, instead of exposing the fields themselves.
I treat the API you expose to derived classes as very similar to the API you expose to other types - it should be a higher level of abstraction than implementation details which you may want to change later.
You should declare them as "protected" instead of private
You are probably looking for a concept called constructor inheritance. You can forward arguments to the base classes constructor - see this example, where the Audi has a flag indicating whether it's an S-Line edition or not:
namespace ConstructorInheritance
{
abstract class Car
{
private int horsePower;
private int maximumSpeed;
public Car(int horsePower, int maximumSpeed)
{
this.horsePower = horsePower;
this.maximumSpeed = maximumSpeed;
}
}
class Audi : Car
{
private bool isSLineEdition = false;
// note, how the base constructor is called _and_ the S-Line variable is set in Audi's constructor!
public Audi(bool isSLineEdition, int horsePower, int maximumSpeed)
: base(horsePower, maximumSpeed)
{
this.isSLineEdition = isSLineEdition;
}
}
class Program
{
static void Main(string[] args)
{
Car car = new Audi(true, 210, 255);
// break here and watch the car instance in the debugger...
}
} }