Sorry for the title i will put here an example of what i want to accomplish:
namespace mdclass
{
class pClass
{
static void Main()
{
tiles<int> tl = new tiles<int>();
tl[0].X = 0;
}
}
class tiles<T> : List<T>
{
public int X
{
//get/set the X-coordonate
}
public int Y
{
//get/set the Y-coordonate
}
}
}
how can i transfer the [0] from the tl[0] in the public int X and work with it?
Create a class for x and y coordinates:
public sealed class Point {
public int X { get; set; }
public int Y { get; set; }
}
Use the Point class to store the coordinates into the list:
public sealed class Program {
public static void Main() {
var tiles = new List<Point>();
tiles.Add(new Point { X = 5, Y = 10 });
tiles[0].X = 15;
}
}
Could you not just make tl public?
Then myInt = mypClass.tl[0].X
A data heirachy like this might work for you (no time to add actual code, sorry!). Then you could implement appropriate getters and setters.
Public class Grid {
List<Row>
}
Public class Row{
List<Point>
}
Public Class Point{
public int X { get; set; }
public int Y { get; set; }
}
Related
I have a List in a class that look like this.
public class Festival
{
public string _festivalName;
public int _showCap = 5;
public List<Show> setList = new List<Show>();
public Festival()
{
}
public void createFestival(Festival z)
{
Show x = new Show();
x.setFestival(z);
}
public void addShow(Band y)
{
setList.Add(y);
}
public void addShow(Preformer x)
{
Preformer y = new Preformer(x);
setList.Add(y);
}
}
The Prefomer class for example look like this:
public class Preformer: Show
{
public bool _gotEncore;
public Preformer(string bandName,string bandHit)
{
this._bandName = bandName;
this._bandHit = bandHit;
}
public Preformer(Preformer t)
{
}
~Preformer() { }
public void setEncore(bool gotEncore)
{
_gotEncore = gotEncore;
}
}
The Base class is Show and the child are Band and Performer.
In the class Festival, i have a list of Shows and I want to show all the details of each performer/ band that in List in a dynamic styled table.
Thank You!
This question already has answers here:
What's the correct alternative to static method inheritance?
(8 answers)
How to use polymorphism or inheritance in static classes?
(4 answers)
Closed 2 years ago.
I have a static class containing several subclasses for managing different constants.
Very different classes I want to implement the same properties depending only on the defined constants.
It looks like this:
public static class A
{
public static class Subclass1
{
public const int Constant1 = 0;
public const int Constant2 = 1;
public static List<int> Elements
{ get { return new List<int> { Constant1, Constant2 }} }
public static int Sum { get { return Elements.Sum(); } }
public static int NegSum { get { return -Elements.Sum(); } }
}
public static class Subclass2
{
public const int Constant3 = 3;
public const int Constant4 = 4;
public static List<int> Elements
{ get { return new List<int> { Constant3, Constant4 }} }
public static int Sum { get { return Elements.Sum(); } }
public static int NegSum { get { return -Elements.Sum(); } }
}
}
so that I can easily access them by
int a = A.Subclass1.Constant1;
List<int> b = A.Subclass1.Elements;
int c = A.Subclass1.Sum;
The code of the Properties Sum and NegSum is always the same.
You see the problem: I need to include them for every subclass again. Is there any way to reuse the code of the properties without implementing them for every single class?
What I would like to do is something like:
public abstract class Base
{
public abstract static List<int> Elements { get; }
public static int Sum { get { return Elements.Sum(); } }
public static int NegSum { get { return -Elements.Sum(); } }
}
public static class B
{
public static class Subclass1 : Base
{
const int Constant1 = 0;
const int Constant2 = 1;
public override static List<int> Elements
{ get { return new List<int> { Constant1, Constant2 }} }
}
public class Subclass2 : Base
{
const int Constant3 = 0;
const int Constant4 = 1;
public override static List<int> Elements
{ get { return new List<int> { Constant3, Constant4 }} }
}
}
Well, I know that in C# Inheritance like this doesn't work for static classes.
Is there any other smart way to implement this?
Maybe try implementing Subclass1 and Subclass2 without static keyword. Like this
public abstract class Base
{
public Base(params int[] elements)
{
this.Elements = new List<int>(elements);
}
public List<int> Elements { get; private set; }
public virtual int Sum { get { return Elements.Sum(); } }
public virtual int NegSum { get { return -Elements.Sum(); } }
}
public static class B
{
public static class Subclass1 : Base
{
const int Constant1 = 0;
const int Constant2 = 1;
public Subclass1() : base(Constant1, Constant2){}
}
public class Subclass2 : Base
{
const int Constant3 = 0;
const int Constant4 = 1;
public Subclass2() : base(Constant3, Constant4){}
}
}
Then add two static properties to class B
public static Subclass1 InstanceSubclass1 {get; private set}
public static Subclass2 InstanceSubclass2 {get; private set}
At the end add static constructor to class B
static B()
{
InstanceSubclass1 = new Subclass1 ();
InstanceSubclass2 = new Subclass2 ();
}
You can now access to your classes by using
B.InstanceSubclass1
What you are wanting will not be possible without some code duplication. C# doesn't handle inheritance with static the same way. While you can't override the static member of a super class, you can use new to hide and reimplement it. The downside to this is you lose the subtype contract that abstract provides, but if you really want your types to be "abstract" and have static members, you are pretty much SOL on that front.
public class Base
{
public static List<int> Elements { get; }
public static int Sum(List<int> Elements) => Elements.Sum();
public static int NegSum(List<int> Elements) => -Elements.Sum();
}
public static class B
{
public sealed class Subclass1 : Base
{
const int Constant1 = 1;
const int Constant2 = 2;
public static new List<int> Elements
{ get => new List<int> { Constant1, Constant2 }; }
public static new int Sum { get => Base.Sum(Elements); }
public static new int NegSum { get => Base.NegSum(Elements); }
}
public sealed class Subclass2 : Base
{
const int Constant3 = 3;
const int Constant4 = 4;
public static new List<int> Elements
{ get => new List<int> { Constant3, Constant4 }; }
public static new int Sum { get => Base.Sum(Elements); }
public static new int NegSum { get => Base.NegSum(Elements); }
}
}
An alternative is that you can use the singleton pattern to create the illusion that you are achieving what you want to achieve. As far as intellisense is concerned, this will produce the exact same effect of accessing the members like B.Subclass1.Sum. The downside being that this would also expose the _Subclass1 and _Subclass2 classes and pollute the namespace, but you will just have to decide if that is an acceptable trade-off.
public abstract class Base
{
public abstract List<int> Elements { get; }
public int Sum { get => Elements.Sum(); }
public int NegSum { get => -Elements.Sum(); }
}
public static class B
{
public static _Subclass1 Subclass1 { get; } = new _Subclass1();
public static _Subclass2 Subclass2 { get; } = new _Subclass2();
public sealed class _Subclass1 : Base
{
const int Constant1 = 1;
const int Constant2 = 2;
public override List<int> Elements
{ get => new List<int> { Constant1, Constant2 }; }
}
public sealed class _Subclass2 : Base
{
const int Constant3 = 3;
const int Constant4 = 4;
public override List<int> Elements
{ get => new List<int> { Constant3, Constant4 }; }
}
}
You could use interfaces and an extension method if you didn't want to have a base class:
public interface IElementsHost
{
List<int> Elements { get; }
}
public static class ElementsExtensions
{
public static int Sum(this IElementsHost host) => host.Elements.Sum();
public static int NegSum(this IElementsHost host) => -host.Elements.Sum();
}
public class Host : IElementsHost
{
public const int Constant1 = 2;
public const int Constant2 = 3;
public List<int> Elements { get; }
= new List<int>(new int[]{ Constant1, Constant2 });
}
// client code
var host = new Host();
var sum = host.Sum();
If you wanted related subclasses to have such capabilities, you'd have to do it with composition. It would look like:
public static class OtherStaticClass
{
public static ElementHost { get; } = new Host();
static OtherStaticClass()
{
Host.Elements.Add(/* some constant, etc. */);
}
}
// client code
var sum = OtherStaticClass.ElementHost.Sum();
Programming newbie here and I've been breaking my head over this for several hours now.
I can make a coordinate object but then I want to make a dot object that can access the coordinate fields from a Coordinate object. How do I "link" these two classes together? And do you have any recommendations for good YouTube videos that explain what I'm missing here? Thanks!
class Coordinate
{
public int X { get; private set; } = 0;
public int Y { get; private set; } = 0;
public Coordinate(int x, int y)
{
x = X;
y = Y;
}
}
class Dot
{
public string color { get; set; }
public Dot(string color, Dot dot)
{
this.Color = color;
}
}
class Program
{
static void Main(string[] args)
{
Coordinate coor1 = new Coordinate(2, 3);
Dot dot1 = new Dot("Blue", coor1);
}
Here is what you are searching for a "linking" your classes. In object-oriented programming this is called composition.
That way you can use functionality and data of Coordinate-instance inside your Dot class.
class Coordinate
{
public int X { get; private set; }
public int Y { get; private set; }
public Coordinate(int x, int y)
{
X = x;
Y = y;
}
}
class Dot
{
public Coordinate coord { get; private set; }
public string color { get; set; }
public Dot(string color, Coordinate coord)
{
this.color = color;
this.coord = coord;
}
}
class Program
{
static void Main(string[] args)
{
Coordinate coor1 = new Coordinate(2, 3);
Dot dot1 = new Dot("Blue", coor1);
Console.WriteLine(dot1.coord.X);
}
}
Note: I also fixed possible typo in Coordinate-constructor (setting X=x and Y=y..)
is there a way to put these into either a 1 D array or a 2 D array. ? i have produced code and it looks a bit untidy as well as long can this be shortened?
double worstPrice = 6.47;
double bestPrice = 0.99;
double CivetCatPrice =29.14;
double whenPrice = 10.50;
double everythingPrice = 319.56;
int bestStock = 3238;
int worstStock = 8;
int civetCatstock = 3;
int whenStock = 37;
int everythingStock = 2;
You can make an array for each doubles and ints like this
double[] priceData = new double[]{ 6.47, 0.99, 29.14, 10.50, 319.56 };
int[] stockData = new int[]{ 3238, 8, 3, 37, 2 };
Alternatively you can use a dictionary if you wish for them to keep their names
Dictionary<string, double> priceDict = new Dictionary<string, double>();
priceDict.Add("worstPrice", 6.47);
//And so on for each double
Dictionary<string, int> stockDict = new Dictionary<string, int>();
priceDict.Add("bestStock", 3238);
//And so on for each int
The values in these can be called like so
double worstMinusBestPrices = priceData[0] - priceData[1]; //For arrays
double worstMinusBestPrices = priceDict["worstPrice"] - priceDict["bestPrice"] //For dictionaries
You could implement a custom class which holds these values as proprties with meaningful names. Then your code will be much more readable, maintainable and robust.
For example (you don't need all of these classes, it should just give you an idea):
public abstract class Animal
{
public Animal(string animalName)
{
this.Name = animalName;
}
//insert properties and methods which all aimals share here
public string Name { get; set; }
}
public class CibetCat : Animal
{
public CibetCat() : base("CibetCat")
{
}
//insert properties and methods which all CibetCats share here
}
Now your class that holds the price and stock informations as well as the reference to the animal itself(CibetCat in your example):
public class AnimalStock // or AnimalPrice or whatever
{
public AnimalStock(Animal animal)
{
this.Animal = animal;
}
public AnimalStock(Animal animal, decimal worstPrice, decimal bestPrice, int bestStock, int worstStock)
{
this.Animal = animal;
this.Worstprice = worstPrice;
this.BestPrice = bestPrice;
this.BestStock = bestStock;
this.WorstStock = worstStock;
}
public Animal Animal { get; set; }
public decimal Worstprice { get; set; }
public decimal BestPrice { get; set; }
public int BestStock { get; set; }
public int WorstStock { get; set; }
// ...
}
Lot of code but not complex. Now You can write this simple and readable code:
Animal cibetCat = new CibetCat();
AnimalStock stock = new AnimalStock(cibetCat);
stock.BestPrice = 0.99m;
stock.Worstprice = 6.47m;
stock.BestStock = 3238;
// ...
Later you can access all these properties(or it's methods) from a single instance.
Console.WriteLine("Animal's best-price is: {0}", stock.BestPrice); // etc
As Alfie pointed out, you could use a dictionary - but you're then referencing things by a string identifier, that you have to remember.
Another way would be to use a class or struct. There are of course many ways to do this, but some include:
public class Things
{
public double worstPrice = 6.47;
public double bestPrice = 0.99;
public double CivetCatPrice =29.14;
public double whenPrice = 10.50;
public double everythingPrice = 319.56;
public int bestStock = 3238;
public int worstStock = 8;
public int civetCatstock = 3;
public int whenStock = 37;
public int everythingStock = 2;
}
Another way would be:
public class Things
{
public double WorstPrice { get; readonly set; }
public double BestPrice = { get; readonly set; }
// etc
public Things(double worstPrice, double bestPrice) // etc
{
WorstPrice = worstPrice;
BestPrice = bestPrice;
}
}
There are pros and cons to both approaches. Another potential is to use a collection of a class/struct to group things and aggregate them in meaningful ways.
Like:
public class Thing
{
public string ThingLabel { get; readonly set; }
public double ThingPrice { get; readonly set; }
public int ThingQuantity { get; readonly set; }
// the value of your stock, calculated automatically based on other properties
public double ThingValue { get { ThingPrice * ThingQuantity; } }
public Thing(string thingLabel, double thingPrice, int thingQuantity)
{
ThingLabel = thingLabel;
// etc
}
}
public void DoStuff()
{
List<Thing> list = new List<Thing>();
Thing thing = new Thing("Civet cat", 500, 10);
list.Add(thing);
list.Add(new Thing("Sea flap flap", 100, 5);
list.Add(new Thing("Nope Rope", 25, 4);
Console.WriteLine("The value of {0}'s stock is: {1}", thing.ThingLabel, thing.Value);
}
and yet another way is to use a base class and create sub classes of your different types. The possibilities are nearly endless! You just have to decide which way works best for you now, you later, and your potential team.
Example:
public class BoundingBox
{
public Vector3Double Positon { get; set; }
public Vector3Double Apothem { get; set; }
public ExtremasForX X;
public BoundingBox(Vector3Double position, Vector3Double size)
{
Positon = position;
X = new ExtremasForX(this);
}
private class ExtremasForX
{
private BoundingBox box;
public ExtremasForX(BoundingBox box)
{
this.box = box;
}
public double Max
{
get { return box.Positon.X + box.Apothem.X ; }
}
public double Min
{
get { return box.Positon.X - box.Apothem.X; }
}
}
}
This code produces an accessibility error: BoundingBox.X has a higher level than it's type.
I would like an inner class that does not have a public constructor, as I only wish to use the class as a namespace for the outer class. How can I do it?
If you really don't want to expose the inner type, you can to have the inner class implement an interface. Then, in the outer class, you expose X as being of the interface type but internally use the inner class' type.
Personally, I would just make the inner class public. Users can't hurt anything by instantiating the class, so it's not a big deal to expose the constructor.
Code for exposing the inner type, without exposing the constructor, via an interface:
public class BoundingBox
{
public Vector3Double Positon { get; set; }
public Vector3Double Apothem { get; set; }
public IExtremasForX X { get { return _x; } }
private ExtremasForX _x;
public BoundingBox(Vector3Double position, Vector3Double size)
{
Positon = position;
_x = new ExtremasForX(this);
}
public interface IExtremasForX {
public double Max { get; }
public double Min { get; }
}
private class ExtremasForX : IExtremasForX
{
private BoundingBox box;
public ExtremasForX(BoundingBox box)
{
this.box = box;
}
public double Max
{
get { return box.Positon.X + box.Apothem.X ; }
}
public double Min
{
get { return box.Positon.X - box.Apothem.X; }
}
}
}
Change the access modifier of class ExtremasForX to public and change its constructor to internal instead of public, like so:
public class BoundingBox
{
public Vector3Double Positon { get; set; }
public Vector3Double Apothem { get; set; }
public ExtremasForX X;
public BoundingBox(Vector3Double position, Vector3Double size)
{
Positon = position;
X = new ExtremasForX(this);
}
public class ExtremasForX
{
private BoundingBox box;
internal ExtremasForX(BoundingBox box)
{
this.box = box;
}
public double Max
{
get { return box.Positon.X + box.Apothem.X ; }
}
public double Min
{
get { return box.Positon.X - box.Apothem.X; }
}
}
}