How to add a property to the sealed class Arc - c#

how can I add two new properties to the sealed Arc class.
I want to extend the class with a double property to hold a double value and a string property to hold the name of the object.
My first try was via the Tag property but this can only hold the double value OR the object name.
The problem is that I created a new user control with 43 arc objects and when the mouse entered an arc another control shows up the value and the name of the entered segment. So every arc uses the SAME MouseEntered function and I want to get the informations via the "object sender".
I hope anyone has a nice idea.

You could use the composite pattern.
class SuperArc
{
Arc Arc { get; set; }
// other properties.
}

You can't. It's sealed. Either:
Create a new class that contains an Arc as a property.
Store a tuple or some other object in Arc.Tag.
Decorate the Arc with attributes
For your particular problem, I would suggest #2 above or to store a Dictionary<Arc, blahblahblah> or Dictionary<string, blahblahblah> (by name) and look up the info you need. #1 is a lot of overhead wrapping all the methods and properties you need for drawing, and probably more hassle than it's worth.

You can't extend sealed clases.
Try creating your own class and having Arc as a class member, and expose this member functions.
Best regards.

Related

Using inheritance as a naming convention

I was wondering about the use cases of inheritance. Specifically, I have a situation in C# where I have an Axis class where you can give the class a string name, among other properties. So you can write (new Axis(“X”)) to create an Axis named X.
Because usually you’ll want to create X, Y and Z axes, I feel inclined to create three subclasses of Axis named X, Y and Z, each of which specifies in the constructor what the Axis name is.
At present there is not a lot of code in the Axis class, so code reuse is pretty minimal (though of course that could change). And to be fair, it’s also not that much trouble to write (new Axis(“X”)) instead of (new X()).
Anyway, what I’m wondering about is whether there are any disadvantages to writing my code like this, or maybe if it’s just not common practice to do it like this. Much obliged!
Imo it depends on what you're going to do with this value:
Use it as a title: I can imagine a graph (are you creating a graph?) with an x-axis to represent time instead. A string constructor parameter is perfectly fine here, even if you decide to always name the x-axis "X".
Use it to identify the axis: if other parts of the code actively look for an "X"-axis, you might want to use an enum instead, ie AxisType.X.
nothing: if the application doesn't depend on this value, perhaps you could use "anonymous axes" instead, and leave out the parameter?
I wouldn't create a subclass unless each subclass has distinct behavior from the others.
Like Damien mentioned, if it's only for making creating them simpler, it's probably a better idea to have a helper method/property for creating them.
public class Axis
{
public Axis(string name)
{
Name = name;
}
public string Name { get; }
public static Axis X { get; } = new Axis("X");
public static Axis CreateX() => new Axis("X");
}
If you have a property, you need to make sure Axis is immutable. You could always return a new one in the property, but that's not what a property should do.
Consider the following.
It is general consider poor practices to have variable names of x and y. names like this give other developers no insight into the nature of what the variable and it's use. The same principal should be used on class naming as well. Creating sub classes called x and y are not very useful names. I would lean on names like xAxis and yAxis to help provide clarity.
Does your XYZ coordinates have different properties or will be called by different methods that are specifically for each type? If not than why use different types. The the sub classes will not be equivalent or interchangeable. So any places that you plan on using them interchangeable would have either refer to base class any or have multiple version in code to handle each type.
If your just trying to short hand the instantiation of the class I would caution against is unless you are under some kind of sizing constraint.

Is it possible to change an object type in C#

I am having some problem in order to meet a client request.
I will try to keep the example very simple just give an idea of the problem and hopefully come up with a solution.
At this point we have a class "Shape" for example, and shape has some specializations, it can be square, triangle etc.
so far so good, everything working great.
Now for some reason my client wants to change a square that already exist in the system into a triangle but keep all the data from shape.
is that possible? any workarounds for that?
You can not change the runtime type of an object. Just create a new triangle, copy over all the relevant values and throw away the square. This may of course become tricky if the square is already referenced by a lot of other objects because you will have to update all references.
If replacing the object is not an option, you will probably have to come up with a generic shape class that can act as any kind of shape. This class could, for example, be a thin wrapper around an instance of one of the concrete shape classes. This enables you to just replace the wrapped square with a new triangle while the outside world can keep all the references to the wrapper class.
It is not possible in terms of replacing the type of an existing object without creating a new object of the desired type and manually updating all references to it (which is highly error-prone) - which I would consider a workaround.
Design-wise, the if the "type" (in the sense of behaviour, not of an actual type in the static type system) needs to be flexible, the problem can be solved with delegation. The object itself would remain the same, but a delegate is exchanged.
You can't change the type but you can solve this with a proper design.
If the idea is that each object is a Shape and it has additional information, which has to be replacable, it makes sense that it would be held as a separate member. For example (pseudo):
public class ShapeContainer
{
public int x { get; set; }
public int y { get; set; }
public ISpecificShape SpecificShape { get; set; }
}
public class Triangle : ISpecificShape
{
// ...
// ...
}
public class Rectange : ISpecificShape
{
// ...
// ...
}
This way, you can change the specific shape.
If you want it to be typed, you could add the following generic Get function to Shape:
GetSpecificShape<T>() where T : ISpecificShape
{
return (T)this.SpecificShape;
}
This will raise an exception if the data types do not match but that's consistent with your design requirements.
What do you think?
What you need is called inheritance.
Here is a model of that :
Create a StrokeStyle class
width
color
type (dashed, solid)
Create a FillStyle class
color
type (solid, gradient)
Create a VectorShape class that has strokeStyle and fillStyle properties (each being an instance of the classes).
Create Square and Triangle class, both being inheriting VectorShape class. They will share VectorShape properties. You will have to replace your square instance by a new Triangle instance and copy the properties you want to keep.
You can also do a single class with a shapetype property wich will be "square" or "triangle"... then you gain the benefit of changing the type without replacing the object. But you wil have to handle the shapetype in all methods ie : computeArea(). And this will lead to a huggly unmanagable code. This is possible but it's the bad way.
You can convert between data types. The results can be placed in a new object. The type of the original object does not change. But usually you only provide a mechanism for this when it makes sense to do so. In the case of converting a square into a triangle, I don't see how that would make sense but maybe there's something about your specific application where it would make sense (ie, convert a square to a triangle with the same size perimeter or area).
See Using Conversion Operators on MSDN for examples of converting between different types.
From Casting and Type Conversions on MSDN:
Because C# is statically-typed at compile time, after a variable is
declared, it cannot be declared again or used to store values of
another type unless that type is convertible to the variable's type.
For example, there is no conversion from an integer to any arbitrary
string. Therefore, after you declare i as an integer, you cannot
assign the string "Hello" to it, as is shown in the following code.
There is a Convert.ChangeType(dObject, typeof(SomeClass));
But for the conversion to succeed, value must implement the IConvertible interface, because the method simply wraps a call to an appropriate IConvertible method. The method requires that conversion of value to conversionType be supported.
Define and implement a virtual Clone() method in your Shape class. You have two "reasonable" options. Whichever implementation you choose you can't just "invent" the data that isn't there - the square has one side size and the triangle has 3.
First option is to manually copy all fields around:
class Shape{
public virtual Shape Clone(Shape target = null){
if (target == null) target = new Shape();
target.Prop1 = this.Prop1;
return target;
}
}
class Square{
public override Shape Clone(Shape target = null){
if (target == null) target = new Square();
base.Clone(target);
if (target.GetType() == typeof(Square)){
target.PropSquare1 = this.PropSquare1; // some casting etc
}
}
}
// change type:
var triangle = new Triangle();
square.Clone(triangle);
Second option, which I prefer trades in performance for convenience. It is to use a serializer to serialize the shape as one kind and deserialize as another. You may need to process the serialized result in-between. Below is a pseudo code version:
class Shape{
public virtual T Clone<T>() where T: Shape{
var data = JsonConvert.Serialize(this);
data = data.Replace("Square","Triangle");
return JsonConvert.Deserialize<T>(data);
}
}

Access field from class where list belong to

let say i have following class:
class Shape
{
public int widht;
public List<Point> points;
}
and in class Point i want to use this widht property from class Shape, so if "point" belong to that list i wish to have possibility to use "container" properties. I also want to serialize then class Shape so I don't think i can use constructor with parameters.
Edit:
I will say how it looks like in my app:
i have class Device
class Device
{
string connection;
List<Task> tasks;
}
and Task
class Task
{
void DoTask()
{
and here i need the connection
}
}
so i just like to do it then foreach(task in task) task.DoTask() but i have to pass additional "this" like task.DoTask(this) or the connection where i think that i should have acces of my container if it allows me.
There's no general concept of the "owner" of an object. After all, the same Point reference could appear in several places. The desire to do this usually indicates a design smell. If you need to give the Point object more information, that's presumably when you're doing something with it - so pass that information to the appropriate method.
One of the simplest ways would be to build an explicit association between these two. For example:
public class Point {
Shape shape;
public Point( Shape shape ) {
this.shape = shape;
}
}
In this particular implementation each point points to a single shape. And you can of course access shape properties from within the point class.
The serialization should not an issue if you can control it.

Class Design with Polymorphism and Inheritance

I currently have the following:
public abstract class CharacterClass
{
public abstract Attribute FirstAttributeBonus { get; }
public abstract Attribute SecondAttributeBonus { get; }
protected Attribute[] attributeBonuses; //2 attribute bonuses, which add 10 to the attributes stored in the array.
protected SKill[] majorSkills; //Major skills for class begin at 30.
protected Skill[] minorSkills; //Minor skills for class begin at 15.
protected IDictionary<int, Character> characterList; //List of characters who apply to this class specifically.
public CharacterClass()
{
}
}
With the idea in mind that whichever class I create will inherit from this base, and also inherit the classes fields as well. For example, one class could be Warrior; the other could be Battlemage, etc.
Is this the right way to perform such a design, while having the derivative constructors initialize the fields? Or is it better to write the classes out without them inheriting these fields?
Edit:
I forgot to mention that all derivatives will be singletons, and I'm changing the name of Class to "CharacterClass", to avoid confusion.
I assume that you don't mean whichever class but rather all game object classes? In that case it might be a good design, if all game object really need those attributes.
The role of an abstract base class is to gather common code there to get rid of repetitions in the subclasses. If all game object subclasses need those fields then it is correct to put them in the base class. If the different game object subclasses initialize those to different values it is correct to defer initialization to the subclasses.
One possibility to force initialization of those fields is to provide a nondefault constructor in the base class, requiring the subclasses to pass init values as parameters to the ctor.
I assume you mean a constructor example? Change your existing
public CharacterClass()
{
}
into something like
public CharacterClass(Attribute[] attributeBonuses,
SKill[] majorSkills, Skill[] minorSkills)
{
if(attributeBonuses == null || majorSkills == null || minorSkills == null)
throw new ArgumentException("Null values are not allowed");
this.attributeBonuses = attributeBonuses;
this.majorSkills = majorSkills;
this.minorSkills = minorSkills;
}
You absolutely need to get a hold of the book called Head Start Design Pattern. You don't need to read the entire book: its first chapter describes the design pattern you are looking to implement.
Basically, you want your Character class to have interfaces that call classes that hold your implementation code such as the skill classes, attribute classes and all the other ones you'll add later. That way, you can add new types of skills and attributes and you'll also be able to modify those at runtime. You DON'T want the character class to hold all the possible implementations. For what you're trying to do, you want to favor object composition instead of inheritance.
Take 20 minutes to read the first chapter: http://oreilly.com/catalog/9780596007126/preview
I think that this is smelling. This code-smell even has a name: God - class.
IMO, it is not a good idea to create one 'mother' (or god) class, where all other classes inherit from.
I see in your base class some properties like MajorSkills. I see that you'll have a class 'BattleImage' that you'll inherit from this base class, but, I don't think that an image has skills.
I would create more specific base-classes, and only inherit from these base-classes if there exists an Is A relationship.
I don't think there's anything particularly wrong with holding protected abstract fields if they are common to all derived classes, though I do recommend the solution that Anders has given.
The part I particularly dislike though, is the IDictionary<int, Character> characterList;.
I'm going to make the assumption that your Character has internally a CharacterClass reference so that you can access the details whenever you need, and as it appears, you will be creating a cycle between Character and CharacterClass. It seems like you're making the CharacterClass have too many responsibilities. I would move the responsibility of holding all Characters of a specific CharacterClass elsewhere.

C# a list or array that accepts all types?

I'm thinking of creating a class in XNA 3.1 that handles the drawing of shadows. I know there are lots of ways to do this but I'm wanting to do something like a List of all the objects that should have a shadow and pass that List to the shadow class so it iterates through each object and draws a shadow.
The reason I want to do it like this is cause I could easily control whether shadows exist or not with just a boolean.
A List for all types is probably unlikely, my backup is a List of type Object but I don't know how to cast the elements in the List which are of type Object back into their respective types so I can access their properties.
My second backup is make all the objects that will have shadows derive from a class called ShadowObject or something and make the List of that type. This is a really easy solution but the reason I'm not doing it yet is cause I don't like the idea of a dummy class just to make something work, but maybe I should start liking it.
My final backup would be to go into each class that will have shadows and have a boolean to see if shadows should be drawn and handle the drawing in the class itself, which I think shouldn't even be considered an option cause if I want to change the shadow mechanics I would have to change it in every class.
So I guess a List for all types is my official question for the public but I'm open to answers, suggestions, and criticism to my backup plans.
Edit: I'm aware of interfaces but my response to that is in the comments for xixonia's answer and after reading up a little more on interfaces I think having a ShadowCaster class would be more appropriate. It can handle all the shadow drawing because all shadows are drawn the same way, I don't need to define it for each object individually like an interface would require me to.
I believe you should use an interface, and make sure all of your "DrawShadow" methods match that interface. This way you can create a list of shadow casters that match the interface.
So long as an object implements that interface, you know you can tell it to draw a shadow. The actual drawing of the shadow will be left up to the object itself, provided the correct device to draw with.
For example:
class Program
{
public static void Main()
{
var shadowCasters = new List<ICastShadow>();
shadowCasters.Add(new Car());
shadowCasters.Add(new Plane());
var castShadows = true;
if (castShadows)
{
foreach (var caster in shadowCasters)
{
caster.DrawShadow(null);
}
}
Console.Read();
}
public class Car : ICastShadow
{
public void DrawShadow(object device)
{
Console.WriteLine("Car Shadow!");
}
}
public class Plane : ICastShadow
{
public void DrawShadow(object device)
{
Console.WriteLine("Plane Shadow!");
}
}
public interface IShadowCaster
{
void DrawShadow(object device);
}
}
When you need to test if your object is capable of casting shadows, you can use the "is" keyword...
if(myTrain is ICastShadow)
{
shadowCasters.Add(myTrain);
}
Hope this helps! :)
edit:
The reason you wouldn't want to use inheritance is if your game objects all draw shadows in different ways, and if some of your derived classes don't cast shadows. For instance:
You have a BrickBuilding and a GlassBuilding. Brick building should cast a shadow, and glass building should not. They both inherit from Building, which inherits from ShadowCaster. Even if all of your shadow-casting classes drew shadows the same way, you would still need to make ShadowCaster's methods virtual, so GlassBuilding could override them and do nothing when that method is called.
Using composition instead of inheritance (i.e: use an interface), you would be able to compose the shadow drawing method on only those classes that actually cast shadows, and you have one less class in your hierarchy (which makes maintainability a breeze).
So what happens when you use an interface and you start repeating the same logic over and over again because your shadow drawing classes all draw shadows the same way? Obviously this isn't the best idea. But if they're all drawing shadows the same way, you can use another class to draw shadows for them. Then comes the "ShadowCaster" class.
The shadow drawing implementation on each object would then call a method on this ShadowCaster to draw the shadow for it. This allows each object the option of drawing shadows in a different way, but also provides a way for each object to use the default shadow drawing implementation. It also provides a way to easily add and remove the ability to draw shadows for specific objects (simple don't let the objects implement the ICastShadow interface).
To take it one step further, you could treat shadow casting just like another drawing method, and create a generalized interface for drawing shadows / particles / reflections / tron-glow, etc, and created different "modules" that do these different things. Instead of having you class implement 'ICastShadows", have it implement "IDrawModules", and then give each class the correct modules at run time.
In other words, you can add a "CastShadow" module to BrickBuilding, and add a "Reflect" module to GlassBuilding, and have your code call "DrawModules" on both objects (from the IDrawModules interface).
Ok this is getting really really long, Hope this helps, and it's not too confusing.
I would suggest reading the first couple chapters of Head First Design Patterns. It's a java-based book, but the principles are the same for most languages.
Instead of a "dummy class" ShadowObject why don't you just create an interface IShadowObject that would expose all necessary methods and use:
List<IShadowObject>
i don't know much about game development but it looks like System.Generic.Collection.List is supported by the XNA framework. That would be your list of any type.
you can use "is" operator to check for type.
public bool check(object obj)
{
return obj is ShadowStuff;
// or obj.GetType() == ShadowStuff
}
to cast :
(ShawdowStuff) obj ;

Categories

Resources